Eagleheart
Eagleheart

Reputation: 53

C++ - Store Pointer in byte array?

Is there any way to store a pointer address inside of a char byte array, byte by byte, and then convert it back to a pointer?

Upvotes: 1

Views: 2450

Answers (2)

M.M
M.M

Reputation: 141648

Yes, you can do:

void *p = bla;

char temp[sizeof p];
std::memcpy(temp, &p, sizeof p);
// ...
std::memcpy(&p, temp, sizeof p);

You may need #include <cstring> for memcpy.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249642

Sure. Just memcpy it:

void* ptr = nullptr;
char buffer[sizeof(void*)];
memcpy(buffer, &ptr, sizeof(void*));

And back:

memcpy(&ptr, buffer, sizeof(void*));

Upvotes: 2

Related Questions