Skip to content
Official PYQ · 2018

GATE CS 2018 Q2 — Programming in C

Explain with AI

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
View worked solution

Answer: A

Let's analyze the memory layout and pointer arithmetic step-by-step:

  1. Structure Definition & Memory Layout:

    The structure Ournode is defined as:

    struct Ournode {
        char x, y, z;
    };

    Since each member is of type char (1 byte), they are stored contiguously in memory with no padding. The offsets from the base address of the structure are:

    • x is at offset 0
    • y is at offset 1
    • z is at offset 2
  2. Initialization:

    The variable p is initialized as:

    struct Ournode p = {'1', '0', 'a' + 2};
    • p.x = '1'
    • p.y = '0'
    • p.z = 'a' + 2, which evaluates to the character 'c' (since the ASCII value of 'a' is 97, 97 + 2 = 99, which is the ASCII value of 'c').
  3. Pointer Arithmetic:

    q is a pointer pointing to p. When we cast it to (char*)q, pointer arithmetic is performed in steps of 1 byte (the size of char):

    • *((char*)q + 1) accesses the byte at offset 1, which corresponds to p.y. Its value is '0'.
    • *((char*)q + 2) accesses the byte at offset 2, which corresponds to p.z. Its value is 'c'.
  4. Output:

    The printf statement prints these characters using the %c format specifier:

    printf("%c, %c", '0', 'c');

    This outputs: 0, c

Therefore, the correct option is A.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions