Reputation: 53
void main(){
int a = 100;
int* pa = &a;
*pa = 999;
}
The above code will make the value of a to 999. But why not the pointers to structures treated the same way?
struct node* head = (struct node*) malloc(sizeof(struct node));
head -> data = 6;
head -> next = NULL;
Why can we not use *head -> data = 6
? And why passing someMethod(pa)
is pass by reference and someMethod(head)
is pass by value? reference
Upvotes: 1
Views: 1653
Reputation: 158
First question's answer, you have got already.
For second Question, Consider three variables, A,B,C where A & C are integer Variables and B is a integer Pointer. Variable names, their values and address(assumed to see a memory map)
has been shown in picture.
see this code
void fun(int *b,int *c)
{
printf("\nfun %d",*b);
b=c;
}
void fun1(int **b, int *c)
{
printf("\nfun1 %d",**b);
*b=c;
}
int main()
{
int a=10;
int c=200;
int *b=&a;
printf("\n %d %d %d",a,*b,c);
fun(b,&c);
printf("\n %d %d %d",a,*b,c);
fun1(&b,&c);
printf("\n %d %d %d",a,*b,c);
return 0;
}
In main()
,a & c are local integer Variables, having different data and b is a integer pointer. We are calling function fun()
like this,
fun(b,&c);
Since, b is a pointer so, we are passing the value of b i.e address of a (1000).
so if we modify the b inside function fun()
, that change will reflect inside the fun()
only.
Now we call the function fun1()
,
fun1(&b,&c)
Here, we are passing the address of b i.e (3000). so, when we modify the b inside the fun1()
, we see the reflection in main()
as well.
so, passing by value means, we want to use values without modifying the original pointer present in calling function( main()
). but we pass by reference, when we need any significant change which should reflect in our calling function( main()
) itself.
I hope, this clears the doubt.
Upvotes: 1
Reputation: 726919
Why can we not use
*head -> data = 6
?
Because ->
is a dereference operator that replaces the asterisk *
. You can rewrite with an asterisk, too
(*head).data = 6
You need parentheses because dot has higher precedence than indirection. Operator ->
has been introduced to make indirection more readable in case of pointers to struct
s.
why passing
someMethod(pa)
is pass by reference andsomeMethod(head)
is pass by value?
It's all pass by value, because pointers are passed by value, too. Passing a pointer lets you reference the original variable and modify it, but the pointer itself is copied.
Upvotes: 6