GATE / CS ARCHIVE

GATE CSE 2018 / QUESTION 2

Reading char members through a pointer

Programming in C · Pointers & Memory · Full GATE CSE 2018 paper

GATE 2018, Q2 1 mark · MCQ
Report issue

Pointers & Memory

Question 2, GATE 2018: C declares struct Ournode { char x,y,z; }; initializes p={'1','0','a'+2}; sets q=&p; and prints printf("%c, %c", *((char*)q+1), *((char*)q+2)). Choices: A 0, c; B 0, a+2; C '0', 'a+2'; D '0', 'c'.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A under conventional layout and character encoding

Method

The cast occurs before pointer arithmetic: a char pointer advances by one byte, whereas adding 1 to a struct pointer would advance by a whole struct. Under the intended layout, offsets 1 and 2 select y and z. The expression 'a'+2 is evaluated numerically during initialization, not printed as source text. The %c conversion prints the represented character without surrounding quote marks. Keep the implementation assumptions below separate from the intended exam output.

Solution

With consecutive char members at byte offsets 0, 1, 2, the two dereferences read y and z. In an ASCII-compatible execution character set, y is the character 0 and z is c from a+2, giving 0, c, A. Strict ISO C permits internal struct padding and does not universally require contiguous alphabetic codes. The result therefore assumes the conventional padding-free char layout and character encoding used by the question.

Original paper, page 4 · Answer key