sizeof struct

Started by
3 comments, last by MaulingMonkey 18 years, 8 months ago
I came across a confusing phenomenon; why is sizeof(myStruct) == 8? struct myStruct { unsigned long numberOne; unsigned short numberTwo; }; If I put the pragmas below around it, the size will be 6, why? When do I need to use this "workaround"? And what does this pragma do? #pragma pack(push, 1) /* ... */ #pragma pack( pop )
Advertisement
I would guess the compiler is padding to align the data to 4-byte increments, and that the pragma overides that by instructing the compiler to pack the data together contiguously.
it's 8 because it's more effecient for 32 bit cpus to access 4 bytes at a time than 2.
Hmm, it seems like we have a couple of these threads each month. Maybe they should mention this in the FAQ.
This extra padding (the extra two bytes which are confusing you) is provided to ensure numberOne is allways on a four byte boundry, which allows for more efficient access. You should never need to use this "workaround", but people often (mis)use it to read files by reading in a big chunk of data and then casting a pointer to that data to a pointer to a specific structure.

The pragma sets (pushes), and then unsets (pops), the "pack" option which controls how to align data - pack( push , 1 ) sets this to 1-byte boundries. Depending on your compiler, I believe the default may be something like 8 (meaning the compiler will pad so that any 8-byte type (e.g. __uint64 or similar) will be aligned on an 8-byte boundry (e.g. the address will look like either: 0x_______0 or 0x_______8).

This topic is closed to new replies.

Advertisement