Reputation: 23
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?
Upvotes: 2
Views: 83
Reputation: 18576
According to the C language standard, bit fields layout is implementation dependend. So it is fine that the size of this struct was 12 bytes on the author's machine but it is 16 on yours(however, it is strange that in the lecture they claim that its size is 12 bytes without pointing out that it is compiler dependend).
Upvotes: 0