Suppose you are compiling on a machine with 1-byte chars, 2-byte shorts,…
2020
Suppose you are compiling on a machine with 1-byte chars, 2-byte shorts, 4-byte ints, and 8-byte doubles, and with alignment rules that require the address of every primitive data element to be an integer multiple of the element’s size. Suppose further that the compiler is not permitted to reorder fields; padding is used to ensure alignment. How much space will be consumed by the following array?
struct {
short s;
char c;
short t;
char d;
double r;
int i;
} A[10]; /*10 element array of structs */
- A.
150 bytes
- B.
320 bytes
- C.
240 bytes
- D.
200 bytes
Attempted by 199 students.
Show answer & explanation
Correct answer: C
Final result: The array occupies 240 bytes (each struct is 24 bytes and there are 10 elements).
Step-by-step layout and padding (sizes and alignments: char=1, short=2, int=4, double=8):
short s (size 2, align 2): placed at offset 0–1.
char c (size 1, align 1): placed at offset 2. Next free offset is 3.
short t (size 2, align 2): needs an even offset, so 1 byte padding is inserted at offset 3; short t is placed at offset 4–5. Next free offset is 6.
char d (size 1, align 1): placed at offset 6. Next free offset is 7.
double r (size 8, align 8): requires offset multiple of 8, so 1 byte padding added at offset 7; double r is placed at offset 8–15. Next free offset is 16.
int i (size 4, align 4): offset 16 is already a multiple of 4, so int i is placed at offset 16–19. Next free offset is 20.
Total used bytes before final padding: 20.
Because the struct must have a size that is a multiple of the largest member alignment (8), round 20 up to 24. So each struct occupies 24 bytes.
Array size for 10 elements: 24 × 10 = 240 bytes.
A video solution is available for this question — log in and enroll to watch it.