C Programming Basics
struct S { char c; int i; char d; };
struct T { int i; char c; char d; };
printf("%zu %zu\n", sizeof(struct S), sizeof(struct T));Assume a typical environment where char is 1 byte and int is 4 bytes, with int placed at addresses that are multiples of 4. Which of the following is the output when the code above is executed?
- A6 6
- B9 6
- C12 8
Show answer and explanation
Answer: C. 12 8
int is placed at an address that is a multiple of 4, so in struct S, 3 bytes of padding are inserted after c, i is placed at byte offset 4, and d at offset 8. In addition, the size of the whole struct is rounded up to a multiple of 4 so that i stays aligned in every element of an array of structs, so 3 bytes are added after the 9 bytes, giving 12 bytes. In struct T, c and d follow i for 6 bytes, which is rounded up to 8 bytes. Ordering members from the largest type down reduces padding.
- A. This is the sum of the member sizes without considering padding (1 + 4 + 1 = 6).
- B. This is the value obtained by considering only the padding before int and not rounding the whole up to a multiple of 4.
- C. Correct. S is 12 bytes including padding, and T is 8 bytes.