IAE Academy

GATE 2018 CS Q.2: solution and answer

GATE 2018 · CSQ.2 · 1 mark · MCQ

Consider the following C program.

#include<stdio.h>
struct Ournode{
    char x,y,z;
};

int main(){
    struct Ournode p = {'1', '0', 'a'+2};
    struct Ournode *q = &p;
    printf ("%c, %c", *((char*)q+1), *((char*)q+2));
    return 0;
}

The output of this program is:

  1. (A)

    0, c

  2. (B)

    0, a+2

  3. (C)

    '0', 'a+2'

  4. (D)

    '0', 'c'

See the question in the paper

Answer and solution

ANSWER

The output is 0, c — option (A).

Official answer: ASource: Official answer key, GATE 2018 CS (IIT Guwahati)

  1. struct Ournode has three char members (x, y, z), each 1 byte with no alignment padding required, so they occupy offsets 0, 1, 2 from the start of p.

  2. Initialization: p.x = '1', p.y = '0', p.z = 'a'+2. The expression 'a'+2 is evaluated once as int arithmetic: 'a' (97) + 2 = 99, which is the char 'c'; so p.z stores 'c'.

  3. q = &p, a struct Ournode* pointing to the same address as p.

  4. (char*)q reinterprets that address as a char pointer: (char*)q+0 = &p.x, (char*)q+1 = &p.y, (char*)q+2 = &p.z.

  5. ((char)q+1) dereferences the byte at offset 1, giving p.y = '0'.

  6. ((char)q+2) dereferences the byte at offset 2, giving p.z = 'c'.

  7. printf("%c, %c", '0', 'c') prints the raw characters with the literal ", " separator from the format string, producing: 0, c.

  8. This matches option (A); (C) and (D) wrongly include quote marks (not produced by %c), and (B) wrongly treats p.z as the two characters 'a' and '+2' instead of the single computed char 'c'.

KEY IDEA

A struct of same-sized char members has no padding, so byte offsets equal member order; casting a struct pointer to char* and indexing lets you read individual member bytes directly, and %c prints only the raw character, never quote marks.

WATCH OUT FOR

Assuming (char*)q+2 lands on garbage/padding, or forgetting that 'a'+2 is evaluated as an int arithmetic expression at initialization time (giving the char 'c') rather than being stored literally as "a+2"; also mistakenly believing %c would print the quotes shown in the option text.

From the GATE 2018 CS paper. Every question of this paper · Download the full paper · All 11 Pointers & arrays questions, with notes

More Pointers & arrays questions