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

相关推荐
顾鉴行思1 分钟前
10 字符串常量到底存在哪里?
c语言·汇编·经验分享
ProgramHelpOa1 分钟前
Optiver 2026 OA 全面复盘|26NG / Intern 最新高频题型整理
人工智能·算法·机器学习
feifeigo1232 分钟前
基于无迹变换的电网概率潮流分析 MATLAB 实现
开发语言·算法·matlab
Java成神之路-4 分钟前
【算法刷题笔记】全题型导航目录
笔记·算法
爱写代码的倒霉蛋6 分钟前
2022年天梯赛L1-8真题解析(哈希+排序)
数据结构·算法
时空系10 分钟前
第13篇:综合实战——制作我的小游戏 Rust中文编程
开发语言·后端·rust
Struggle_975513 分钟前
算法知识-倍增算法
算法
计算机安禾16 分钟前
【计算机网络】第5篇:网桥学习与生成树算法——环路拓扑中的路径收敛问题
学习·计算机网络·算法
CoderCodingNo17 分钟前
【信奥业余科普】C++ 的奇妙之旅 | 19:内存的门牌号——地址与指针的设计原理
开发语言·c++
fie888919 分钟前
基于遗传算法的机械故障诊断MATLAB程序
算法·机器学习·matlab