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

相关推荐
多恩Stone1 分钟前
【3DV 进阶-9】Hunyuan3D2.1 中的 MoE
人工智能·pytorch·python·算法·aigc
CC.GG3 分钟前
【Qt】Qt背景与环境搭建
开发语言·qt
xu_yule3 分钟前
数据结构(4)链表概念+单链表实现
数据结构·算法·链表
你的冰西瓜10 分钟前
C++23 新特性详解:相较于 C++20 的主要改进
开发语言·c++·stl·c++23
沐知全栈开发10 分钟前
HTMLCollection 对象
开发语言
代码栈上的思考17 分钟前
二叉树的层序遍历:4道例题讲解
算法·宽度优先·队列在宽度优先搜索中的应用
froginwe1118 分钟前
Ruby 日期 & 时间处理指南
开发语言
Evand J18 分钟前
【MATLAB例程】二维指纹对目标的一段轨迹定位,锚点数量可调。输出位置真值、估计值对比,附代码下载链接
开发语言·数据库·matlab
wjs202420 分钟前
SQL NOW() 函数详解
开发语言
杰瑞不懂代码20 分钟前
【公式推导】AMP算法比BP算法强在哪(二)
python·算法·机器学习·概率论