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 is:
View worked solution
Answer: C
Let us trace the execution of the function call printxy(1, 1) step-by-step:
- Initialization:
The function is called with arguments
x = 1andy = 1. Inside the function, local variablesxandyare initialized to1. - Step 1:
x = 0;The value of
xis updated to0. - Step 2:
ptr = &x;The pointer
ptris assigned the address of the local variablex. Thus,ptrnow points tox. - Step 3:
y = *ptr;The value at the address stored in
ptr(which is the current value ofx, i.e.,0) is assigned toy. Hence,ybecomes0. - Step 4:
*ptr = 1;The value at the address pointed to by
ptris set to1. Sinceptrpoints tox, this direct assignment changes the value ofxto1. - Step 5:
printf("%d, %d", x, y);At this point, the values of the variables are:
x = 1y = 0
Thus, the output printed is
1, 0.
Therefore, the correct option is C.
Free practice · Your answers on this page are not saved.
