Question
Consider the following function implemented in C:
void printxy(int x, int y) {
int *ptr;
x = 0;
ptr = &x;
y = *ptr;
*ptr = 1;
printf("%d, %d", x, y);
}
The output of invoking printxy(1, 1) is
Official answer and solution
- Official answer
- C
- From
- Official GATE 2017 answer key
Solution
Trace the pointer assignments and memory modifications step by step.
Trace the execution of printxy(1, 1):
- Parameters
xandyare initialized to 1 (local copies passed by value). int *ptr;: Declares a local pointer variableptr.x = 0;: The local variablexbecomes 0.ptr = &x;: The pointerptrnow stores the address of local variablex.y = *ptr;: Dereferencesptr(value ofx, which is 0) and assigns it to local variabley. Thus,ybecomes 0.*ptr = 1;: Modifies the memory location pointed to byptr(which isx) to 1. Thus,xbecomes 1.printf("%d, %d", x, y);: Prints the current values ofx(1) andy(0).
The printed output is 1, 0, corresponding to option C.
Final answer
C
Common trap
Assuming *ptr = 1 changes y because y had received *ptr earlier; y = *ptr copied the value, not the reference.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 2
- Question
- 14 of 65, printed as CS Q.14
- 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.