How is the size of a struct with Bit Fields determined/measured? How is the size of a struct with Bit Fields determined/measured? c c

How is the size of a struct with Bit Fields determined/measured?


It is the order that matters. The following code will give Output: 8

#include<stdio.h>typedef struct size{        unsigned int b:32;        unsigned int a:1;        unsigned int c:1;}mystruct;int main(int argc, char const *argv[]){        mystruct a;        printf("\n %lu \n",sizeof(a));        return 0;}

Unsigned int is a 32 bit integer, occupying 4 bytes. Memory is allocated contiguously in memory.


Option 1:

unsigned int a:1;       // First 4 bytes are allocatedunsigned int b:31;      // Will get accomodated in the First 4 bytesunsigned int c:1;       // Second 4 bytes are allocated

Output: 8


Option 2:

unsigned int a:1;       // First 4 bytes are allocatedunsigned int b:32;      // Will NOT get accomodated in the First 4 bytes, Second 4 bytes are allocatedunsigned int c:1;       // Will NOT get accomodated in the Second 4 bytes, Third 4 bytes are allocated

Output: 12


Option 3:

unsigned int a:1;       // First 4 bytes are allocatedunsigned int b:1;       // Will get accomodated in the First 4 bytesunsigned int c:1;       // Will get accomodated in the First 4 bytes

Output: 4


Option 4:

unsigned int b:32;      // First 4 bytes are allocatedunsigned int a:1;       // Second 4 bytes are allocatedunsigned int c:1;       // Will get accomodated in the Second 4 bytes

Output: 8


You don't say whether you know what bitfields are, but I'll assume you do.

On your implementation, evidently unsigned int is 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 single unsigned int, hence the need for 8 bytes in the first example. 3 bitfields totalling 3 bits certainly do fit into an unsigned 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 b is 32 bits, it fills a whole unsigned int on its own, forcing both of a and c to occupy their own unsigned int, before and after the middle one. Hence, 12 bytes.


Alignment

The compiler is rounding the size of the structure to 32 bits, the size of each object it may try to reference to 32 bits, and at the same time it is preserving the order of your bit fields.

So if you have a 32-bit item in the middle and 1-bit items on each side, that's 3 32-bit words to allocate and so: 12 bytes.

For the other two cases, it's just a question of how few 32-bit objects your bitfield sequence can be packed into, while still preserving field order.