Reputation: 71
Please have a look at code below :
#include <stdio.h>
void main()
{
int a=30;
int *var=&a;
Change(&var);
printf("%d %d",*var,a);
}
int Change(int**ptr)
{
**ptr=40;
}
#include <stdio.h>
void main()
{
int a=30;
int *var=&a;
Change(var);
printf("%d %d",*var,a);
}
int Change( int *ptr)
{
*ptr=40;
}
The output from both programs is 40 40
We are passing the copy of address of var so why it is reflected in actual main function and producing output 40 40
?
Why both of these programs are producing same output?
Upvotes: 0
Views: 122
Reputation: 4319
It seems to me you need the following illustration to get the answer on your q:
Upvotes: 2
Reputation: 5409
&var
passes the address of var
and Change
uses double pointer because, var
is pointing to address of a
. So, Derefrencing single pointer on &var
(address of var) will point to the value stored in var
i.e., a
's address, so again derefrencing it, will point to the value of a
i.e., 30
.
For single pointer Change
, I think, you should figure that out now from the above details.
Upvotes: 1
Reputation: 8209
The output is the same because you write 40
via the same pointer to int
. In the second case you pass pointer-to-int, which you successfully dereference with *
operator and obtain lvalue with type int
, to which you then write 40
. In the first case you pass pointer-to-pointer-to-int. And then you do double dereferencing: **ptr
or the same as *(*ptr)
. Inner *
is applied first and makes the expression with type pointer-to-int inside braces, and that pointer-to-int is the same as was passed to Change()
in the second case. And at the end - outer *
works just like for the second case.
Upvotes: 1
Reputation: 1402
Both programs are equivalent. In first one, you passing pointer to pointer (i.e. address of pointer variable), and then dereferencing it twice. In second one, you are are just passing pointer (i.e. address of actual variable) and dereferencing it once.
Upvotes: 2