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

相关推荐
CC.GG9 分钟前
【Qt】Qt初识
开发语言·qt
数据门徒15 分钟前
《人工智能现代方法(第4版)》 第4章 复杂环境中的搜索 学习笔记
人工智能·算法
永远都不秃头的程序员(互关)18 分钟前
查找算法深入分析与实践:从线性查找到二分查找
数据结构·c++·算法
Sunsets_Red19 分钟前
二项式定理
java·c++·python·算法·数学建模·c#
菜鸟‍19 分钟前
【论文学习】SAMed-2: 选择性记忆增强的医学任意分割模型
人工智能·学习·算法
业精于勤的牙21 分钟前
模拟退火算法
算法·机器学习·模拟退火算法
罗湖老棍子24 分钟前
【例9.10】机器分配(信息学奥赛一本通- P1266) 机器分配(洛谷P2066)
算法·动态规划·多重背包
好评12430 分钟前
C/C++ 内存管理:摆脱野指针和内存泄漏
开发语言·c++·内存管理·c/c++
Arva .34 分钟前
读写锁 (ReadWriteLock)
java·开发语言
灰灰勇闯IT35 分钟前
虚拟机性能优化实战:从基础调优到深度压榨性能
开发语言·学习·性能优化·虚拟机