Skip to content
GATEiit

GATE CSE 2018 Q12: C struct accessed through a char pointer

Syllabus topic: Programming in C

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:

Try it: multiple choice: exactly one correct option

Select one option
Wrong answer costs 1/3 mark in GATE.
Show answer and explanation

Answer: A (official GATE 2018 final answer key)

Concept used: Struct members of type char are laid out consecutively, so casting the struct pointer to char* and adding offsets reaches y and z; %c prints the character itself without quotes.

Concept notes

Loading notes…

First step: Work out the values stored in y and z ('a'+2 is a character code), then note what %c prints for each.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Programming in C

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2018 CS question paper and final answer key, organised by IIT Guwahati. Question paper · Answer key