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?

  1. A6 6
  2. B9 6
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. uint32_t and uint8_t are 32-bit and 8-bit unsigned integer types, and the environment is little-endian. Which of the following is the output when the code above is executed?
  2. Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?
  3. Which of the following is the output when the code above, which uses the macro SQUARE defined with #define, is executed?
  4. The header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?
  5. Which of the following is the output when the code above is written inside the main function and executed?