Search code examples
c++pointerscastingdereference

C++ Convert number to pointer of type?


I have the following bit of code:

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

Now I want anotherInt to point to the same value as anInt, but the current code makes anotherInt point to the value of memAddr. How can I set anotherInt to point to the value of anInt using only memAddr?


Solution

  • You can type cast a pointer directly to an integer. This will make anotherInt point to the same int as anInt.

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

    Alternatively you can have memAddr store the address of the pointer (a pointer to a pointer) and use it as such:

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