Question
Consider the following C program.
#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);
}
The output of the program is _____.
Official answer and solution
- Official answer
- 140
- From
- Official GATE 2015 answer key
Solution
Trace pointer initialization, pointer arithmetic, and indirection step-by-step.
Analyze the arrays:
a = {10, 20, 30, 40, 50}has base address&a[0]:apoints toa[0] = 10a + 1points toa[1] = 20a + 2points toa[2] = 30a + 3points toa[3] = 40a + 4points toa[4] = 50
p = {a, a + 3, a + 4, a + 1, a + 2}is an array of pointers toint:p[0] = &a[0]p[1] = &a[3]p[2] = &a[4]p[3] = &a[1]p[4] = &a[2]
int **ptr = p;initializesptrto&p[0].ptr++;advancesptrby one element, soptrnow points top[1].- Compute expressions in
printf("%d%d", ptr - p, **ptr):ptr - p: pointer subtraction between&p[1]and&p[0]evaluates to the index difference, which is .*ptrevaluates top[1], which isa + 3(pointing toa[3]).**ptrevaluates to*(a + 3) = a[3] = 40.
The format string "%d%d" outputs 1 immediately followed by 40, resulting in 140.
140
Inserting an unintended space between the two values, or confusing pointer difference ptr - p (which is in units of sizeof(*p), yielding 1) with byte offset.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 3
- Question
- 36 of 65, printed as CS Q.26
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.