On a typical 64-bit system with 4-byte int, what does sizeof return for struct S { char c; int i; };?
Correct answer
A. 8, because padding aligns the int to 4 bytes
15 views
A. 8, because padding aligns the int to 4 bytes
15 views
Compilers insert padding so each member starts at an address aligned to its own size, so one byte for the char is followed by three padding bytes before the 4-byte int, making the struct 8 bytes. The members still occupy only 5 bytes of real data; declaring int first and char second moves the padding to the end but still gives 8 bytes, because the struct's size must be a multiple of its strictest alignment. Using #pragma pack or an attribute removes the padding at the cost of slower unaligned access.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.