Reputation: 1803
Is there a way to store the address of a pointer into an arbitrary variable (e.g. an int
) and to use this variable again to assign the address of a second pointer?
I know you can easily do
int* p1;
int* p2;
p2 = p1;
What I'm looking for is something like this
int* p1;
int* p2;
long addr_p1 = (long)p1;
p2 = doMagicCast(addr_p1);
Thanks for any advise
Upvotes: 1
Views: 110
Reputation: 50775
This is the correct C++ way:
#include <cinttypes>
int main() {
int* p1;
int* p2;
std::uintptr_t addr_p1 = reinterpret_cast<std::uintptr_t>(p1);
p2 = reinterpret_cast<int*>(addr_p1);
}
You need to use std::uintptr_t
instead of long
because there is no guarantee that a long
can hold a pointer.
But on 32 bit platform (where long
and pointers usually have 32 bits) your initial approach using long may work.
Upvotes: 3