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

相关推荐
许彰午18 小时前
95_Python内存管理与垃圾回收
开发语言·python
多加点辣也没关系19 小时前
JavaScript|第13章:原始类型的方法
开发语言·javascript·ecmascript
এ慕ོ冬℘゜19 小时前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
QXWZ_IA19 小时前
1库1图1批是什么?千寻位置公安地图数据体系详解
科技·算法·能源·媒体·交通物流·政务
c2385620 小时前
Bug 猎手入门指南
c++·算法·bug
chouchuang20 小时前
day-030-综合练习-笔记管理器
开发语言·笔记·python
Reart21 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
云空21 小时前
《Three.js 3D实例大全》
开发语言·javascript·3d·three.js
techdashen21 小时前
Go 1.26 新增 `bytes.Buffer.Peek`:只看数据,不移动读取位置
开发语言·后端·golang