Question

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:

Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2018 answer key

Solution

Trace memory layout of the struct members and apply byte-level pointer arithmetic.

The structure struct Ournode contains three char members: x, y, and z. Since sizeof(char) == 1 and all members have 1-byte alignment, there is no padding between them:

  • Offset 0: x = '1'
  • Offset 1: y = '0'
  • Offset 2: z = 'a' + 2 = 'c' (since ASCII value of 'a' plus 2 is 'c')

Pointer q points to p. Cast (char*)q treats p as a pointer to the first byte:

  • ((char*)q + 1) points to offset 1 (y), dereferencing gives '0'.
  • ((char*)q + 2) points to offset 2 (z), dereferencing gives 'c'.

printf ("%c, %c", ...) prints the character values separated by comma and space, producing 0, c.

Final answer

A

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2018 Computer Science and Information Technology (CS)
Question
12 of 65, printed as CS Q.2
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.