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

相关推荐
半桶水专家5 小时前
go语言中的结构体嵌入详解
开发语言·后端·golang
长安er6 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓6 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
在屏幕前出油6 小时前
二、Python面向对象编程基础——理解self
开发语言·python
小白菜又菜6 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
阿方索7 小时前
python文件与数据格式化
开发语言·python
登山人在路上7 小时前
Nginx三种会话保持算法对比
算法·哈希算法·散列表
写代码的小球8 小时前
C++计算器(学生版)
c++·算法
AI科技星8 小时前
张祥前统一场论宇宙大统一方程的求导验证
服务器·人工智能·科技·线性代数·算法·生活
weixin_440730508 小时前
java结构语句学习
java·开发语言·学习