It would print 10
if you do this
*q = i
in the called function.
Change the content of that variable whose address is with you in the called function in the local variable q
. Don't change the content of the local variable q
.
You asked me why? Will explain...
This is what happened when you called the function and printed the value. Well this is not an exhaustive list but this points out the key things that will help in this context.
You got the address of the variable i
in p
.
Then you pass it to the called function.
Called function now has a local variable whose content is same as that of p
.
Now you change the content of that local variable with the address of the global variable i
.
Then function ends.
Rest in peace - local variable q
. It is dead.
Then you again access *p
in main()
- meaning you looking for what value there is in the address contained in p
.
you get 20
.
Is there any other way to get 10
?
Well there is
func(&p);
And then you do this
void func(int **q){
*q = &i;
}
Now you print *p
you will get 10
.
Know few things clearly, no matter what C
is pass by value. Even here also q
is a local variable. But now we have the address of p
of main()
in q
. So when you write *q=&i
then you are basically going to the address of p
from main()
and then write there the address of global variable i
. Then you come back. q
is again lost. Then you print it - as you change to the original variable (p
), the content there is 10
.
Code-1
func(p);
then in func()
void func(int *q){
*q = i;
}
Code-2
func(&p);
then in func()
void func(int **q){
*q = &i;
}