【问题标题】:C++ Convert number to pointer of type? [closed]C ++将数字转换为类型的指针? [关闭]
【发布时间】:2015-01-19 14:50:27
【问题描述】:

我有以下代码:

int* anInt = new int(5);
uintptr_t memAddr = (uintptr_t)&anInt;
Log("memAddr is: " + std::to_string(memAddr));
int* anotherInt = (int*)&memAddr;
Log("anInt is: " + std::to_string(*anInt));
Log("anotherInt is: " + std::to_string(*anotherInt));

现在我想让 anotherInt 指向与 anInt 相同的值,但是当前代码使 anotherInt 指向 memAddr 的值。如何仅使用 memAddr 将 anotherInt 设置为指向 anInt 的值?

【问题讨论】:

  • ........什么?!
  • int* anotherInt = (int*)*memAddr;
  • 不要使用 C 风格的强制转换。
  • 您的第四行是潜在的别名违规,并且可能由于对齐而导致约束违规。
  • 如果我做 int* anotherInt = (int*)*memAddr;然后我得到错误:'*' 的操作数必须是一个指针

标签: c++ pointers casting dereference


【解决方案1】:

您可以将指针直接类型转换为整数。这将使anotherInt 指向与anInt 相同的int。

uintptr_t memAddr = (uintptr_t)anInt;
...
int* anotherInt = (int*)memAddr;

或者,您可以让memAddr 存储指针的地址(指向指针的指针)并像这样使用它:

uintptr_t memAddr = (uintptr_t)&anInt;
...
// only works if the variable "anInt" is still alive
int* anotherInt = *(int**)memAddr;

【讨论】:

  • 你确实是对的,我想通了这一点,但决定使用不同的,更好的标识符方法:)
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多