Questions about C bitfields

Because a and c are not contiguous, they each reserve a full int’s worth of memory space. If you move a and c together, the size of the struct becomes 8 bytes.

Moreover, you are telling the compiler that you want a to occupy only 1 bit, not 1 byte. So even though a and c next to each other should occupy only 3 bits total (still under a single byte), the combination of a and c still become word-aligned in memory on your 32-bit machine, hence occupying a full 4 bytes in addition to the int b.

Similarly, you would find that

struct s{
unsigned int b;
short s1;
short s2;
};

occupies 8 bytes, while

struct s{
short s1;
unsigned int b;
short s2;
};

occupies 12 bytes because in the latter case, the two shorts each sit in their own 32-bit alignment.

Leave a Comment