For struct S { char a; int b; char c; }; with 4-byte ints and 4-byte alignment, what is sizeof(struct S)?
Correct answer
A. 12
17 views
A. 12
17 views
Structure padding inserts three bytes after a so that b starts at offset 4, and the total is rounded up to a multiple of the strictest alignment, giving 12 bytes for offsets 0, 4 and 8 plus tail padding. Reordering members as int, char, char fits the same data into 8 bytes, which matters for large arrays and wire formats. Packing directives change the layout but can cost unaligned access penalties.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.