What does the following program print?
#include<stdio.h>
void f(int *p, int *q) {
p=q;
*p=2;
}
int i=0, j=1;
int main() {
f(&i, &j);
printf("%d %d\n", i,j);
return 0;
}View worked solution
Answer: D
Let's trace the execution of the program step-by-step:
-
Initialization:
The global variables are initialized as:
i = 0,j = 1 -
Function Call:
In
main(), the functionf(&i, &j)is called.- The local pointer
pinfis initialized with the address ofi(i.e.,p = &i). - The local pointer
qinfis initialized with the address ofj(i.e.,q = &j).
- The local pointer
-
Inside Function
f:p = q;: This reassigns the local pointerpto point to the same memory location asq. Now,ppoints toj(i.e.,p = &j). Note that this change is local tofand does not affect the variablei.*p = 2;: This dereferencespand modifies the value at that address. Sincepnow points toj, this statement updates the value ofjto2.
-
Print Statement:
After returning to
main(), the values of the global variables are printed:iremains unchanged:0jhas been modified to:2
Thus, the program prints 0 2.
Free practice · Your answers on this page are not saved.
