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

相关推荐
suhan1 分钟前
【数据结构】五、树:7.哈夫曼树、哈夫曼编码
数据结构·算法·排序算法
kkhimself9 分钟前
POJ-3126
算法
suhan19 分钟前
【数据结构】五、树:6.平衡二叉树AVL
数据结构·算法·排序算法
suhan20 分钟前
【数据结构】五、树:5.二叉排序树BST
数据结构·算法·排序算法
爱读书的小胖37 分钟前
80. 删除有序数组中的重复项 II
java·数据结构·算法
雪域迷影37 分钟前
Python Django 7 小时课程
开发语言·python·django
Escalating_xu1 小时前
【C 语言】编译和链接:从源文件、目标文件到可执行程序完整解析
c语言·开发语言
臻选云栗子1 小时前
PCDN跑不起来?先别甩锅给平台,问题可能出在这
算法·程序员
C++ 老炮儿的技术栈1 小时前
std::atomic 是什么
linux·c语言·网络·c++·visual studio
小画家~1 小时前
vue3 里面的 itemList.reduce
前端·数据结构·算法