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

相关推荐
健忘的派大星1 小时前
需求激增800%!2025年第一硬通货:懂大模型、云计算和硬件的“前沿部署工程师”!
人工智能·算法·架构·langchain·云计算·大模型学习·大模型教程
lntu_ling2 小时前
Python-基于Haversine公式计算两点距离
开发语言·python·gis算法
ShineWinsu8 小时前
对于C++:继承的解析—上
开发语言·数据结构·c++·算法·面试·笔试·继承
pp起床8 小时前
动态规划 | part05
算法·动态规划
小付同学呀8 小时前
C语言学习(五)——输入/输出
c语言·开发语言·学习
GuangHeAI_ATing8 小时前
国密算法SSD怎么选?这3款国产固态硬盘安全又高速
算法
梦幻精灵_cq8 小时前
学C之路:不可或缺的main()主函数框架(Learn-C 1st)
c语言·开发语言
雨泪丶9 小时前
代码随想录算法训练营-Day34
算法
消失的旧时光-19439 小时前
C++ 多线程与并发系统取向(二)—— 资源保护:std::mutex 与 RAII(类比 Java synchronized)
java·开发语言·c++·并发
Yzzz-F9 小时前
牛客寒假算法训练营2
算法