+17 votes
2.2k views

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;
}
1. $2 \ 2$
2. $2 \ 1$
3. $0 \ 1$
4. $0 \ 2$

edited | 2.2k views
0
Why would someone pass address of global variable to a function??

## 2 Answers

+29 votes
Best answer
 p=q; // now p and q are pointing to same address i.e. address of j
*p=2;// value of j will be updated to 2


Hence, answer is (D) 0 2

by Boss (42.6k points)
edited by
+7 votes

int  i=0, j=1;

The above statement declares and initializes two global variables.

void f(int *p ,int *q)
{
% A %   p=q  // The address stored in pointer 'q' is assigned to pointer'p'
% B %   *p=2  //The value at the address stored in pointer 'p' is set as 2.
}

Now in the main function the function 'f' is called with the  address of variable 'i'   and 'j' as parameters.

Let us assume address of i=100 and address of j=200.

So the statement A in the definition of function f changes the value of the pointer 'p' from 100 to 200 as the pointer 'p' takes the address of pointer 'q'.

So after statement A the pointer 'p' also stores the address of j.

And in the statement B the value at address stored in the pointer 'p' is set to 2 this means the value of j is changed to 2.

Because of this the printf function in the main will print the value of i=0 and the value of j=2.

Therefore the output will be  0  2

by (375 points)
0
I have a doubt. In function "f" no value is being returned,then also value of J will get changed?
0
@Divyanka, we are sending address of the variable and modifying the value at that address which will definitely change the value of the variable.
0
ok. thank u
Answer:

+7 votes
5 answers
1
+4 votes
2 answers
2
+19 votes
3 answers
3
+22 votes
2 answers
4
+10 votes
5 answers
6
+28 votes
7 answers
7