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

相关推荐
此方ls几秒前
机器学习聚类算法二——DBSCAN(Density-Based Spatial Clustering of Applications with Noise)
算法·机器学习·聚类
add45a4 分钟前
C++中的原型模式
开发语言·c++·算法
代码s贝多芬的音符4 分钟前
Android NV21 转 YUV 系列格式
android·开发语言·python
2401_844221325 分钟前
C++类型推导(auto/decltype)
开发语言·c++·算法
2201_753877796 分钟前
高性能计算中的C++优化
开发语言·c++·算法
无限进步_6 分钟前
深入解析C++容器适配器:stack、queue与deque的实现与应用
linux·开发语言·c++·windows·git·github·visual studio
hans汉斯6 分钟前
基于区块链和语义增强的科研诚信智能管控平台
人工智能·算法·yolo·数据挖掘·区块链·汉斯出版社
2501_945425156 分钟前
分布式系统容错设计
开发语言·c++·算法
冷小鱼8 分钟前
机器学习极简入门:从外卖预测到AI核心算法
人工智能·算法·机器学习
阿成学长_Cain13 分钟前
Linux 命令:ldconfig —— 动态链接库管理命令
java·开发语言·spring