【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 分钟前
手写一个KMP算法:从原理到工程级实现
c语言
Hello eveybody12 分钟前
介绍一下背包DP(C++)
开发语言·c++·动态规划·dp·背包dp
代码中介商19 分钟前
C语言链表完全指南:从单节点到链表管理
c语言·算法·链表
『昊纸』℃32 分钟前
C语言程序设计从入门到进阶【比特鹏哥c语言2023完整版视频教程】(c语言基础入
c语言·函数·常量·编程教程·变量作用域
Run_Teenage43 分钟前
Linux:线程互斥,线程锁
运维·开发语言·jvm
小小de风呀1 小时前
de风——【从零开始学C++】(四):类和对象(下)
开发语言·c++·算法
覆东流1 小时前
第10天:python元组
开发语言·后端·python
CSCN新手听安1 小时前
【Qt】系统相关(一)内容简介,事件概念,事件的处理
开发语言·c++·qt
不想写代码的星星1 小时前
重识 std::tuple:一个被低估的编译期异构容器
开发语言·c++
aqiu1111111 小时前
[特殊字符]【算法日记 14】数论入门神题:最大公约数与最小公倍数的“乘积守恒定律”
算法