我有以下代码:
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的值。如何将anotherInt设置为仅使用memAddr指向anInt的值?
答案 0 :(得分:0)
您可以直接键入一个指针到整数。这将使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;