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

相关推荐
Hello eveybody6 小时前
学习C++的好处
开发语言·c++
爱编码的小八嘎6 小时前
C语言完美演绎9-10
c语言
hhb_6186 小时前
Perl脚本自动化日志分析与数据批量处理实操案例
开发语言·自动化·perl
wjs20246 小时前
XPath 实例
开发语言
十五年专注C++开发6 小时前
CMake基础: Qt之qt5_wrap_ui
开发语言·c++·qt·ui
南境十里·墨染春水6 小时前
C++日志 1——日志系统的概念与分类
开发语言·c++
jf加菲猫6 小时前
第16章 容器类
开发语言·c++·qt·ui
垦利不6 小时前
TS基础篇
开发语言·前端·typescript
人道领域6 小时前
从零实现一个轻量级 RPC 框架:通信协议与动态代理的核心原理
开发语言·网络·qt
阿Y加油吧6 小时前
二刷 LeetCode:118. 杨辉三角 & 198. 打家劫舍 复盘笔记
笔记·算法·leetcode