Consider the following function implemented in C: void printxy(int x, int y) {…
2017
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:
- A.
0,0
- B.
0,1
- C.
1,0
- D.
1,1
Attempted by 261 students.
Show answer & explanation
Correct answer: C
Key idea: function parameters are passed by value, and the pointer manipulates the local x variable.
Initial values: x = 1, y = 1 (parameters are copies).
x = 0 sets the local x to 0.
ptr = &x makes ptr point to the local x variable.
y = *ptr assigns the current value of x (which is 0) to y, so y becomes 0.
*ptr = 1 writes 1 into x through the pointer, so x becomes 1.
At printf time the values are x = 1 and y = 0.
Final output: 1,0
A video solution is available for this question — log in and enroll to watch it.