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.](../../assets/questions/CS-2015-S3-Q43-1.webp)
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.