What does the following program print? #include voidf(int*p, int*q) { p = q;…
2010
What does the following program print?
#include
voidf(int*p, int*q)
{
p = q;
*p = 2;
}
inti = 0, j = 1;
intmain()
{
f(&i, &j);
printf("%d %d \n", i, j);
getchar();
return0;
}
- A.
2 2
- B.
2 1
- C.
0 1
- D.
0 2
Attempted by 244 students.
Show answer & explanation
Correct answer: D
Key idea: pointer parameters are passed by value; assigning to the parameter changes only the local pointer, not the caller's pointer.
Initial values: i = 0, j = 1.
Call f(&i, &j): inside f, p is a local copy pointing to i and q points to j.
The statement p = q makes the local p point to the same object as q (that is, j).
Then *p = 2 stores 2 into j. i is never modified.
Therefore the program prints: 0 2
A video solution is available for this question — log in and enroll to watch it.