【C语言】C tips

1. How to solve warning: cast to pointer from integer of different size and vice versa:

cpp 复制代码
#include <stdio.h>

int main() {
    void *p = NULL;
    int a = 3;
    p = (void *)a;
    a = (int)p;

    printf("%ld\n", p);
    printf("%ld\n", a);

    return 0;
}

The above code has the following warnings when compiling:

cpp 复制代码
/tmp/0pubXc3fmS.c: In function 'main':
/tmp/0pubXc3fmS.c:7:9: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    7 |     p = (void *)a;
      |         ^
/tmp/0pubXc3fmS.c:8:9: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
    8 |     a = (int)p;
      |         ^
/tmp/0pubXc3fmS.o

Converting pointer/data to (unsigned) long before casting to required data types can eliminate this warning: (intptr_t works the same)

cpp 复制代码
#include <stdio.h>

int main() {
    void *p = NULL;
    int a = 3;
    p = (void *)(long)a;
    a = (int)(long)p;

    printf("%ld\n", p);
    printf("%ld\n", a);

    return 0;
}

2.

相关推荐
CarIise2 分钟前
Java实训阶段查漏补缺复习笔记1
java·开发语言·笔记
事圆则缓3 分钟前
Kotlin 泛型方差实战:out、in、星投影与类型擦除
android·开发语言·kotlin
Code_Solitude20 分钟前
c语言:二分法的完整补充
c语言·开发语言·算法
一切皆是因缘际会21 分钟前
掌控信息论:同源星际通信基础理论
人工智能·算法·ai
智鸟科技GemeOpen开发者智能设备27 分钟前
MQTT智能通断器GSCW1M2P · 开发者实战指南
开发语言·物联网·智能家居
水饺编程37 分钟前
第1章,[Win32 章节]:Windows 简史
c语言·c++·visual studio
青柠之夏cc1 小时前
前端拖拽功能原生实现,不引入拖拽库完成业务
开发语言·前端·python
ym hyd 1111 小时前
题库建立与考试系统源码 Java+SpringBoot+Vue3 前后分离
java·开发语言·vue.js·spring boot·毕设
OKkankan1 小时前
Python 高阶语法(一):高阶函数、闭包、lambda 与 functools——从底层真正理解装饰器
开发语言·python
geovindu2 小时前
rust: Facade Pattern
开发语言·后端·设计模式·rust·外观模式