Question
What is printed by the following ANSI C program?
#include<stdio.h>
int main(int argc, char *argv[])
{
int x = 1, z[2] = {10, 11};
int *p = NULL;
p = &x;
*p = 10;
p = &z[1];
*(&z[0] + 1) += 3;
printf("%d, %d, %d\n", x, z[0], z[1]);
return 0;
}Official answer and solution
- Official answer
- D
- From
- Official GATE 2022 answer key
Solution
Trace pointer assignments and array modifications step by step.
Step-by-step program trace:
int x = 1, z[2] = {10, 11};sets , , and .int *p = NULL; p = &x;makes point to variable .*p = 10;assigns the value 10 to . Now .p = &z[1];updates to point to .*(&z[0] + 1) += 3;: Here&z[0]is a pointer to the first element of array . Adding 1 moves the pointer to&z[1]. Dereferencing yields the lvalue . Adding 3 gives .- Variable is not modified, so .
printf("%d, %d, %d\n", x, z[0], z[1]);prints10, 10, 14.
Final answer
Option (D)
Common trap
Overlooking that *(&z[0] + 1) modifies z[1], not z[0].
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2022 Computer Science and Information Technology (CS)
- Question
- 21 of 65
- 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.