#include <stdio.h>
typedef struct size
{
unsigned int a:1;
unsigned int b:31;
unsigned int c:1;
} mystruct;
int main()
{
mystruct a;
printf("%d", sizeof(a));
return 0;
}
- With
int b:31, the output is 8. - With
int b:1, the output is 4. - With
int b:32, the output is 12.
Can somebody explain the reason for this?
You don’t say whether you know what bitfields are, but I’ll assume you do.
On your implementation, evidently
unsigned intis a 32 bit integer, occupying 4 bytes. This accounts for the first and second examples. Clearly 3 bitfields totalling 33 bits don’t fit into a singleunsigned int, hence the need for 8 bytes in the first example. 3 bitfields totalling 3 bits certainly do fit into anunsigned int, hence only 4 bytes in the second example.Furthermore, a bitfield cannot span multiple integers. This accounts for the third example. I can’t remember whether that’s a requirement of the standard, or just a detail of your implementation. Either way, since
bis 32 bits, it fills a wholeunsigned inton its own, forcing both ofaandcto occupy their ownunsigned int, before and after the middle one. Hence, 12 bytes.