In C, the structures are laid out almost exactly as you specify in the code. Similar to C # StructLayout.Sequential.
The only difference is the alignment of the elements. This never reorders data elements in the structure, but can resize the structure by inserting โpadโ bytes in the middle of the structure. The reason for this is to make sure that each member starts at the border (usually 4 or 8 bytes).
For example:
struct mystruct { int a; short int b; char c; };
The size of this structure is usually 12 bytes (4 for each member). This is because most compilers by default make each member the same size as the largest in the structure. Thus, char will take 4 bytes instead of one. But it is very important to note that sizeof (mystruct :: c) will still be 1, but sizeof (mystruct) will be 12.
It is difficult to predict how the structure will be complemented / aligned by the compiler. Most will be by default, as I explained above, some by default will not pad / align (also sometimes called โpackagedโ).
The method for changing this behavior is very dependent on the compiler; there is nothing in the language indicating how this should be handled. In MSVC, you should use #pragma pack(1) to disable alignment (1 says aligns everything to 1 byte boundaries). In GCC, you should use __attribute__((packed)) in your structure definition. See the documentation for your compiler to find out what it does by default and how to change this behavior.
SoapBox May 01 '10 at 5:26 a.m. 2010-05-01 05:26
source share