UGC-NET Oct 2020 · Arrays & Matrix Representation

MCQ · 2 marks · Problem PROG-DSTR-0073

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 */
  1. A
    $150$ bytes
  2. B
    $320$ bytes
  3. C
    $240$ bytes
  4. D
    $200$ bytes

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionLay out one struct with natural alignment (offsets in bytes):\[\begin{array}{ll} \text{short } s & 0\text{-}1\\ \text{char } c & 2\ (\text{pad }3)\\ \text{short } t & 4\text{-}5\\ \text{char } d & 6\ (\text{pad }7)\\ \text{double } r & 8\text{-}15\\ \text{int } i & 16\text{-}19\end{array}\]That is 20 bytes, but the struct must be a multiple of its largest alignment (8, for the double) so that every element of the array is aligned: size \(=24\).\[10\times24=240\ \text{bytes}.\]Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com