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

相关推荐
ValhallaCoder2 小时前
hot100-栈
数据结构·python·算法·
爱编码的小八嘎4 小时前
第3章 Windows运行机理-3.1 内核分析(2)
c语言
xuzhiqiang07245 小时前
Java进阶之路,Java程序员职业发展规划
java·开发语言
MediaTea6 小时前
Python:生成器表达式详解
开发语言·python
WW_千谷山4_sch6 小时前
洛谷B3688:[语言月赛202212]旋转排列(新解法:deque双端队列)
数据结构·c++·算法
Zachery Pole6 小时前
【代码随想录】二叉树
算法
漂流瓶jz7 小时前
UVA-11214 守卫棋盘 题解答案代码 算法竞赛入门经典第二版
c++·算法·dfs·aoapc·算法竞赛入门经典·迭代加深搜索·八皇后
浮生09197 小时前
DHUOJ 基础 88 89 90
算法
v_for_van8 小时前
力扣刷题记录7(无算法背景,纯C语言)
c语言·算法·leetcode
先做个垃圾出来………8 小时前
3640. 三段式数组 II
数据结构·算法