Reputation: 23
#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);
getchar();
return 0;
}
This code prints 0,2,why it does'nt print 0,1 because after *p=2 the value of j is assigned 1 right?can anyone help me
Upvotes: 0
Views: 88
Reputation: 11377
Here is what happens:
statement i j p q
-----------------------------------------
int i = 0, j = 1; 0 1 - -
f(&i, &j); 0 1 &i &j
p = q; 0 1 &j &j
*p = 2; 0 2 &j &j
printf("%d %d \n", i, j); 0 2 - -
Upvotes: 0
Reputation: 15062
"because after
*p = 2;
the value ofj
is assigned by1
right?"
No. You seem to confuse here something very hard in terms of control flow and scope. The definition of f
is placed before the definitions of the global variables i
and j
.
That doesn't mean that the global variables get assigned after the function.
int i = 0, j = 1;
are definitions of i
and j
(declaration with immediate initializations) at global scope, not assignments.
The value of j
2
after the call to f
is correct because:
j
is passed by reference to f
and its address is assigned to the pointer parameter q
.q
is assigned to the pointer p
.p
is dereferenced then which points to j
in the caller and assigns 2
to j
.Upvotes: 0
Reputation: 34583
"after *p=2
the value of j
is assigned 1
right?"
No, function f()
ends at the closing }
brace, and
j
was assigned the value of 1
before main()
begins.
The line
int i = 0, j = 1;
could equally well be further up, before function f()
.
Upvotes: 0
Reputation: 398
Inside f
you are assigning the pointer p
the pointer value of q
.
Means - after p = q;
, both p
and q
point to the same int which is j
.
That's why you get 0,2.
Upvotes: 1