我们如何使用这样的调用函数返回内存区域的地址:
// memory_region malloc'ed before this
uint64 address = get_memory_region_address (memory_region);
printf(">> memory_region (address) = 0x%lX\n", address);
printf(">> memory_region (address) = %p\n", address);
uint64 get_memory_region_address (int* memory_region) {
uint64* address_of_memory = 0;
address_of_memory_region = (uint64) memory_region;
return address_of_memory;
}
最佳答案
保证能够存储指针的正确整数类型是 intptr_t
或 uintptr_t
。
7.18.1.4 能够保存对象指针的整数类型
以下类型指定有符号整数类型,其属性是任何有效的 void 指针都可以转换为该类型,然后转换回 void 指针,结果将与原始指针进行比较:intptr_t
以下类型指定无符号整数类型,其属性是任何有效的 void 指针都可以转换为该类型,然后转换回 void 指针,结果将与原始指针进行比较:uintptr_t
不幸的是,这些类型是可选的
您的代码应该是:
uintptr_t get_memory_region_address (int* memory_region) {
address_of_memory_region = (uintptr_t) memory_region;
return address_of_memory;
}
uintptr_t address = get_memory_region_address (memory_region);
printf(">> memory_region (address) = %p\n", (void *) address);
如果要控制地址的格式,可以将 uintmax_t
转换为 ptrdiff_t
printf(">> memory_region (address) = %0xjX\n", (uintmax_t) address);
或
printf(">> memory_region (address) = %0xtX\n", (ptrdiff_t) address);
引用文献:
-
ptrdiff_t
: 7.17 常用定义<stddef.h>
-
uintmax_t
: 7.18.1.5 最大宽度整数类型<stdint.h>
- 格式化:7.19.6 格式化输入/输出函数,特别是 7.19.6.1 fprintf 函数§7
关于c - 获取内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31819403/