struct MyRect
{
int x, y, cx, cy;
char name[100];
};
int main()
{
MyRect mr;
mr.x = 100;
mr.y = 150;
mr.cx = 600;
mr.cy = 50;
strcpy(mr.name, "Rectangle1");
MyRect* ptr;
{
unsigned char bytes[256];
memcpy(bytes, &mr, 256);
ptr = (MyRect*)bytes;
}
printf("X = %d\nY = %d\nCX = %d\nCY = %d\nNAME = %s\n",
ptr->x, ptr->y, ptr->cx, ptr->cy, ptr->name);
return 0;
}
I was just testing how to put a struct/class in an array of bytes, and was suprised when it compiled and worked, the printf prints all the values which i set in the mr variable.
just a little confused to what exactly “ptr” is pointing to? has it allocated memory for ptr somewhere?
ptris still pointing to the address ofbytes. Or, what was once calledbytes. Even though you’ve putbytesinto its own block and the variable is semantically inaccessible outside of that block, the memory sticks around unmodified until the function exits. This is a typical implementation technique, but is undefined by the standard, so don’t depend on it.