GATE / CS ARCHIVE

GATE CSE 2015 SET 3 / QUESTION 43

GATE CSE 2015 Set 3 Q43

Programming in C · Pointers & Memory · Full GATE CSE 2015 Set 3 paper

GATE 2015 Set 3, Q43 2 marks · NAT
Report issue

Pointers & Memory

Question 43, GATE 2015: What is the intended printed output of this C program? Also distinguish that output from its portability limitation.
#include <stdio.h>
int main() { static int a[]={10,20,30,40,50}; static int *p[]={a,a+3,a+4,a+1,a+2}; int **ptr=p; ptr++; printf("%d%d",ptr-p,**ptr); }
There is no separator between the two decimal conversions.
Tap to enlarge
Answer & solution

Official answer: 140

Our answer: 140 under compatible printf type convention

1. After ptr++, ptr=p+1, so ptr−p=1 and **ptr=*(a+3)=40.

2. The adjacent decimal conversions produce 140. Pointer subtraction has type ptrdiff_t, which need not be int; %d is portable only when its promoted type is int. Otherwise the format mismatch is undefined behavior. Use %td for ptr−p, or cast this known-small difference to int, to guarantee the intended display.

Original paper, page 68 · Answer key