c - 将 int 变量的值赋给 int 指针

标签 c pointers casting int assign

我在嵌入式软件项目中使用了以下 C 函数。它还用于硬件验证,而不是用于生产。

void reg_read(int addr) {
   int result;
   int* reg_addr = (int*)(addr); // I cast the value of the addr variable to the reg_addr pointer hoping that it would point to the address stored in addr
   result = (*reg_addr); // this should trigger a read transaction on the AXI interface of the ARM CPU that I'm simulating
}
// later on...in the main function
reg_read(0x08000704);

嵌入式软件在模拟环境中运行(使用QEMU+SystemC),我可以看到AXI读取事务是否发生。在这种情况下,它不会发生。

但是,如果我向指针分配一个常量值,例如 int* reg_addr = (int*)0x08000704;,则会发生 AXI 事务。

我假设编译器在每种情况下都会生成不同的指令。我还尝试将 reg_addr 声明为 volatile int* reg_addr; 但它也不起作用。

是否有一种可移植且兼容的方法将 int 变量的值转换为 int 指针?

最佳答案

您的问题是:

Is there a portable and compliant way of casting the value of an int variable to an int pointer?

没有。从评论中总结:

Conversion of an integer to a pointer is implementation defined - Antti Haapala

建议您使用 uintptr_t 或类似的,这是 Eugene Sh 的一个很好的建议。

以uintptr_t为例

uintptr_t = unsigned integer type capable of holding a pointer

来自 Microsoft Visual C++ 头文件 vadefs.h 的 vadefs.h 文件定义为:

#ifdef _WIN64
    typedef unsigned __int64  uintptr_t;
#else
    typedef unsigned int uintptr_t;
#endif

通过这种方式,如果针对 x86 进行编译,它将解析为 32 位数据类型,而对于 x64,则解析为 64 位数据类型。

关于c - 将 int 变量的值赋给 int 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441789/

相关文章:

c++ - automake undefined reference

c - 两个正数相乘在 C 中返回负数

c - fwrite 失败取决于先前的 fwrite

c - scanf 不起作用

c - 在 C 中是否允许/安全地在具有不同大小的结构之间进行转换?

java - 使用返回父类(super class)对象的父类(super class)方法 - Java

c - 如何测量 Linux 上 C 语言的执行时间

c - 套接字编程-setsockopt : Protocol not available?

c - Delphi 中通过引用传递的指针(从 DLL 导入函数)

c# - 为什么在检查对象是否等于 null 之前先转换为 null?