c++ - How does this work? copying anything into an array of bytes (chars) -


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 testing how put struct/class in array of bytes, , suprised when compiled , worked, printf prints values set in mr variable.

just little confused "ptr" pointing to? has allocated memory ptr somewhere?

ptr still pointing address of bytes. or, once called bytes. though you've put bytes own block , variable semantically inaccessible outside of block, memory sticks around unmodified until function exits. typical implementation technique, undefined standard, don't depend on it.


Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -