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

相关推荐
冷雨夜中漫步8 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
HABuo9 小时前
【linux文件系统】磁盘结构&文件系统详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
颜酱10 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_7369191010 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi98783810 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
2501_9449347310 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
DuHz11 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女11 小时前
TRSV优化2
算法
黎雁·泠崖11 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
代码游侠12 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法