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

相关推荐
勇往直前plus32 分钟前
从文件到屏幕:Python/java 字符编码、解码、文本处理的底层逻辑解析
java·开发语言·python
无限进步_36 分钟前
面试题 02.04. 分割链表 - 题解与详细分析
c语言·开发语言·数据结构·git·链表·github·visual studio
zh_xuan37 分钟前
kotlin Flow的用法
android·开发语言·kotlin·协程·flow
Mr YiRan5 小时前
C++面向对象继承与操作符重载
开发语言·c++·算法
一只鹿鹿鹿7 小时前
智慧水利一体化建设方案
大数据·运维·开发语言·数据库·物联网
没有医保李先生9 小时前
字节对齐的总结
java·开发语言
蚊子码农9 小时前
算法题解记录--239滑动窗口最大值
数据结构·算法
liliangcsdn9 小时前
A3C算法从目标函数到梯度策略的探索
算法
Elastic 中国社区官方博客9 小时前
使用 Elastic 进行网络监控:统一网络可观测性
大数据·开发语言·网络·人工智能·elasticsearch·搜索引擎·全文检索
Codefengfeng9 小时前
Python Base环境中加包的方法
开发语言·python