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

相关推荐
longlongzihan14 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
落魄实习生14 小时前
Agent Scope Java 2.x 系列【7】工具使用
java·开发语言·ai
封印师请假去地球钓鱼14 小时前
边解边变的问题:从“决策依赖“一词出发
人工智能·算法
茉莉玫瑰花茶14 小时前
GO [ 方法 ]
开发语言·后端·golang
今晚打老虎15 小时前
c++之提高A(前缀和)(第三课)
数据结构·c++·算法
狗凯之家源码网15 小时前
微博图床 PHP 系统搭建与实战应用指南
android·开发语言·php
不会就选b16 小时前
算法日常・每日刷题--<贪心>26
数据结构·算法
乌暮16 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习
2601_9622186117 小时前
C语言中三种库的编译和使用方法
开发语言·c++
铅笔小新z17 小时前
【C语言】操作符
c语言