Stas Jaro
Stas Jaro

Reputation: 4885

How can I get a struct from a specific memory location?

I have the memory location of a struct stored as an integer. How can I retrieve the struct stored at that location and make a pointer to the object at that location?

Structure object;
int memLocation = &object;

Structure objectCopy = (objectAtLocation) memLocation;
Structure *objectPointer = (pointerToLocation) memLocation;

Upvotes: 1

Views: 590

Answers (4)

lvella
lvella

Reputation: 13433

Structure *objectPointer = (Structure *)memLocation;
Structure ObjectCopy = *objectPointer;

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

The usual is a cast:

Structure *object = (Structure *)memLocation;

Upvotes: 0

japreiss
japreiss

Reputation: 11251

Using ints instead of pointers is very bad form, going back even to the first edition of K&R. So what you're doing is bad. But assuming you have no choice...

if Object is a Structure, then &object is a Structure *. So the proper un-cast is basically your line 3:

Structure *objectPointer = (Structure *) memLocation;

Upvotes: 6

Andrey Starodubtsev
Andrey Starodubtsev

Reputation: 5292

int memLocation = (int)&object;

Structure *objectPointer = (Structure *) memLocation;
Structure object;
memcpy( &object, (void*)memlocation, sizeof( Structure ) );

Upvotes: 2

Related Questions