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

相关推荐
xiaoye-duck7 分钟前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
BackCatK Chen9 分钟前
C语言学习栏目目录
c语言·保姆级教程·c语言入门·c语言学习栏目目录
Hx_Ma161 小时前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
期待のcode2 小时前
原子操作类LongAdder
java·开发语言
极客数模2 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
A_nanda3 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
lly2024063 小时前
C 语言中的结构体
开发语言
JAVA+C语言3 小时前
如何优化 Java 多主机通信的性能?
java·开发语言·php
青岑CTF4 小时前
攻防世界-Ics-05-胎教版wp
开发语言·安全·web安全·网络安全·php
Li emily4 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股