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

相关推荐
孤廖3 分钟前
吃透 C++ 栈和队列:stack/queue/priority_queue 用法 + 模拟 + STL 标准实现对比
java·开发语言·数据结构·c++·人工智能·深度学习·算法
驰羽11 分钟前
[GO]GORM中的Tag映射规则
开发语言·golang
dllxhcjla24 分钟前
07 标识符命名规则
c语言
非凡的世界32 分钟前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php
BanyeBirth32 分钟前
C++动态规划——LIS(最长不下降子序列)
算法·动态规划
小龙报33 分钟前
《算法通关指南---C++编程篇(3)》
开发语言·c++·算法·visualstudio·学习方法·visual studio
凤山老林38 分钟前
排序算法:详解插入排序
java·开发语言·后端·算法·排序算法
郝学胜-神的一滴1 小时前
Effective STL 第5条:区间成员函数优先于单元素成员函数
开发语言·c++·程序人生·stl·软件工程
知星小度S1 小时前
算法训练之多源BFS
算法·宽度优先
2201_758875441 小时前
LeetCode:19. 删除链表的倒数第 N 个结点
算法·leetcode·链表