【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.

相关推荐
dvvvvvw1 小时前
调用函数两点间的距离.c
c语言
shangjian0073 小时前
AI大模型-评价指标-相关术语
人工智能·算法
Live&&learn4 小时前
算法训练-数据结构
数据结构·算法·leetcode
胡萝卜3.05 小时前
掌握C++ map:高效键值对操作指南
开发语言·数据结构·c++·人工智能·map
松岛雾奈.2305 小时前
机器学习--PCA降维算法
人工智能·算法·机器学习
电子_咸鱼5 小时前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
sweet丶6 小时前
适合iOS开发的一种缓存策略YYCache库 的原理
算法·架构
哈茶真的c6 小时前
【书籍心得】左耳听风:传奇程序员练级攻略
java·c语言·python·go
是宇写的啊6 小时前
算法—滑动窗口
算法
沐知全栈开发6 小时前
ionic 选项卡栏操作详解
开发语言