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

相关推荐
努力学习的小廉2 分钟前
【QT(二)】—— 初识QT
开发语言·qt
爱学习的小邓同学2 分钟前
C++ --- map/set的使用
开发语言·c++
梓德原3 分钟前
【C语言】C语言如何向系统接要存
java·c语言·算法
weixin_421133414 分钟前
JShielder
开发语言
酸钠鈀4 分钟前
段式LCD 显存重映射 通用程序
c语言
却话巴山夜雨时i8 分钟前
84. 柱状图中最大的矩形【困难】
算法
MSTcheng.8 分钟前
【C++进阶】继承(下)——挖掘继承深处的奥秘!
开发语言·c++
RisunJan9 分钟前
【HarmonyOS】鸿蒙开发语言的选择
开发语言·华为·harmonyos
学困昇9 分钟前
Linux基础开发工具(上):从包管理到“进度条”项目实战,掌握 yum/vim/gcc 核心工具
linux·运维·开发语言·数据结构·c++·vim
雨落在了我的手上10 分钟前
C语言入门(二十五):自定义类型:结构体
c语言·开发语言