【问题标题】:Get the hexadecimal address of a variable as uintptr_t获取变量的十六进制地址为 uintptr_t
【发布时间】:2018-05-23 04:59:20
【问题描述】:
int y = 1;
int *x = &y;  
printf("%p\n",x); // instead of printing, get this into variable of type unintptr_t

我想将地址x 放入uintptr_t 类型的变量中

有没有办法在 C 中做到这一点?

【问题讨论】:

  • 我错过了什么? uintptr_t ptr = (uintptr_t)x; ?
  • 如果不重复,则与 stackoverflow.com/q/18545212/694576 相关。
  • @John3136n (uintptr_t)x; 缺少通过void* 所需的演员表。

标签: c pointers casting type-conversion


【解决方案1】:

不是特别难……

uintptr_t z = (uintptr_t)x;

请注意,此转换的结果是实现定义的;您唯一的保证是,如果您将z 转换回int *,您将获得原始指针。

顺便说一句,没有“十六进制地址”这样的东西;地址是地址,它们可以被视为您最喜欢的任何基数的数字,以十六进制显示它们只是一种约定(有一些优点)。

【讨论】:

  • 详细信息:x 不是 void* 或类似的。从int* 转换为(uintptr_t) 的定义不是。 6.3.2.3 3 建议 uintptr_t z = (uintptr_t)(void*)x; C11 7.20.1.4 1. “如果你将 z 转换回一个 int * 你会得到原来的指针。”几乎与规范一致,转换需要经过void * 并且得到一个等效的指针,可能不是原来的。
【解决方案2】:

您可以通过将 x 的地址显式类型转换为 uintptr_t 来存储该值。

uintptr_t z = (uintptr_t)&x;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2016-11-04
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多