+ 4
I think the output of this program should 1. But program give 4, can anyone explain?
#include <stdio.h> struct bits{ unsigned int b1:1; unsigned int b2:1; unsigned int b3:1; unsigned int b4:1; unsigned int b5:1; unsigned int b6:1; unsigned int b7:1; unsigned int b8:1; }pr; int main() { printf("%ld",sizeof(struct bits)); return 0; } /* Its output should be 1 byte because struct contains bitfields and when calculate overall size of struct should be 8 bit means 1 byte . There is no case of structure padding because size of struct is 1 byte . So why its size become 4 byte */
4 Answers
+ 4
But why you expected the size to be 1?
+ 2
I'm not exactly an expert on this but basically your CPU has 32 or 64 physical wires that go to RAM ("bus width") so it will always read 4/8 bytes of memory and never less than that.
Say you have your 1-byte `bits` struct in memory location 0x0000 and a 4-byte struct called `cheese` directly after that in locations 0x0001 - 0x0004.
If your CPU wants to read `cheese` from RAM it will have to do two read operations: 0x0000 - 0x0003 and 0x0004 - 0x0007. That's because the CPU can only read memory in this 4 byte grid, and `cheese` is misaligned.
If `bits` is padded to 4 bytes, the problem disappears. It's a waste of space but makes the program faster.
I hope that made sense!
+ 1
Structure padding *is* the answer! Your struct is 1 byte in size but will be padded to 4 bytes.
0
But why