I was going through the lecture notes for the MIT open courseware on practical programming in C about structure padding:
In it, I understood why the following structure has a size of 16:
struct foo {
short s;
union {
int i;
char c;
}u;
unsigned int flag_s : 1;
unsigned int flag_u : 2;
unsigned int bar;
}
To minimize the size of the structure, the author rearranged the fields from largest to smallest in size:
struct foo {
union {
int i;
char c;
}u;
unsigned int bar;
short s;
unsigned int flag_s : 1;
unsigned int flag_u : 2;
}
And the author said that the size of the structure should now be 12. However, on my Windows 32 bit machine, I'm still getting an output of 16 for the struct size. Why is that?
It's only when I move the 'short s' field below the bit fields that I get a struct size of 12. Is this because the bit fields must start at a 4 byte boundary on account of being an unsigned integer? Therefore in the structure above, there will still be 2 bytes of padding after the 'short s' field?