C++ 将数字转换为类型的指针

C++ Convert number to pointer of type?

本文关键字:类型 指针 转换 数字 C++      更新时间:2023-10-16

我有以下代码:

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));

现在我希望另一个Int指向与anInt相同的值,但是当前的代码使另一个Int指向memAddr的值。如何设置另一个Int以仅使用memAddr指向anInt的值?

可以通过键入直接指向整数的指针。这将使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;