Reputation: 123
In the code below output is coming 20 and explanation is given that inside fun()
, q
is a copy of the pointer p
. So if we change q
to point something else then p
remains unaffected. What is the mechanism of function making copy of pointers.
Why p
is not printing 10 when it stores the address of q
.
void fun(int *p)
{
static int q = 10;
p = &q;
}
int main()
{
int r = 20;
int *p = &r;
fun(p);
printf("%d", *p);
getchar();
return 0;
}
Upvotes: 0
Views: 320
Reputation: 8449
There are two different variables, both called p
.
One of them is declared in main()
, the other in fun()
(the variables declared in the parameter list are local to the function). They don't conflict because they are local variables in different functions, but it does look confusing.
Note that the same code would be produced is the references in fun()
were called pp
instead of p
, but you wouldn't be confused to thinking them the same variable.
Upvotes: 0
Reputation: 103733
explanation is given that inside fun(), q is a copy of the pointer p
No. The p
in fun
is a copy of the p
in main.
So if we change q to point something else
q
is not a pointer. You can't make it point to something else, or point to anything at all.
What is the mechanism of function making copy of pointers.
The argument in the function call:
fun(p); // this p here
is copied to the parameter in the function definition:
void fun(int *p) // this p here
Why p is not printing 10 when it stores the address of q.
Because p
doesn't store the address of q
. At least, not the p
in main, who's dereferenced value you are printing. Only the p
in fun
points to q
. But that is a local variable to the function, and you are not doing anything with it.
Upvotes: 0
Reputation: 2917
"if we change q to point to something else" -- q does not point, it is not a pointer. It is an integer. If what you meant is "If we change q's value" such as by
q = 12
Then two things happen.
*p does change, from 10 to 12, because *p means "value at"
Finally "why is p not printing 10"
The p in your main function is different from the p in your "fun" function. They start off with the same value, since you pass it (fun(p)) but when you change it (p = &q) you are changing the p in fun, not the p in main. So p remains pointing at &r (not &q) and so *p is 20
Upvotes: 0
Reputation: 122433
Because the function fun
pass arguments by value. If you want to modify variables outside the function, you need pointers. Since you want to modify a int *
pointer outside the function, you need a int **
pointer:
void fun(int **p) //here
{
static int q = 10;
*p = &q;
}
int main()
{
int r = 20;
int *p = &r;
fun(&p); //and here
printf("%d", *p);
return 0;
}
In C++, you can use pass-by-reference in a similar way.
Upvotes: 2