如何从特定的内存位置获取结构?

时间:2012-03-05 15:51:00

标签: c memory pointers

我将结构的内存位置存储为整数。如何检索存储在该位置的结构并在该位置创建指向该对象的指针?

Structure object;
int memLocation = &object;

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

4 个答案:

答案 0 :(得分:6)

使用int而不是指针是非常糟糕的形式,甚至回到第一版K& R。所以你正在做的事情很糟糕。但假设你别无选择......

如果ObjectStructure,则&objectStructure *。因此,适当的拆解基本上就是你的第3行:

Structure *objectPointer = (Structure *) memLocation;

答案 1 :(得分:2)

int memLocation = (int)&object;

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

答案 2 :(得分:0)

通常是演员:

Structure *object = (Structure *)memLocation;

答案 3 :(得分:0)

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