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

相关推荐
帅那个帅10 小时前
PHP里面的抽象类和接口类
开发语言·php
咖啡の猫16 小时前
Python字典推导式
开发语言·python
leiming616 小时前
C++ vector容器
开发语言·c++·算法
SystickInt17 小时前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
CS Beginner17 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
FJW02081417 小时前
Python_work4
开发语言·python
JAY_LIN——817 小时前
指针-数组
c语言·排序算法
Xの哲學17 小时前
Linux流量控制: 内核队列的深度剖析
linux·服务器·算法·架构·边缘计算
大学生资源网18 小时前
java毕业设计之儿童福利院管理系统的设计与实现(源码+)
java·开发语言·spring boot·mysql·毕业设计·源码·课程设计
JasmineWr18 小时前
JVM栈空间的使用和优化
java·开发语言