I am creating a simple binary search tree.When I am calling the add method using head pointer,changes made in the method are not reflected to this head pointer.It still points null.
struct node *add(struct node *root,int data)
{
if (root==NULL)
{
root=(struct node *) malloc(sizeof(struct node));
root->data=data;
root->left=NULL;
root->right=NULL;
return root;
}
else
{
if (data<=root->data)
{
root->left=add(root->left,data);
}
else
{
root->right=add(root->right,data);
}
return root;
}
}
I am calling the function as
struct node *head=NULL;
add(head,1);
add(head,3);
add(head,15);
In my understanding, on calling the add method, root=head, so head would point to the same memory location where root is pointing and should be updated with the changing value of root accordingly.
UPDATE
head=add(head,1);
When you pass a pointer (node* here), you just copy the value of the memory address it's pointing to, you can change the contents of this address in the function, but the pointer outside of it would still contain the same address.
Initially you have head = NULL
, it's not pointing anywhere. When you call the function you create a local variable called root
, and copy the value of the pointer (NULL) into that. You then allocate some space and change root
to point there, but changes to the local variable would be lost once you leave the function, and head
outside will continue holding the value NULL
. You actually lost the memory you allocated as no one points there any longer (valgrind could have told you that).
If you passed &head
to the function instead (the type would then be node**
, note that you'd have to use *root
inside the function this way), the changes would be made directly on the outside variable (thanks to the fact c would actually pass the address where main() allocated it on the stack directly to the function).
By the way, in c++, Passing the value by reference would emulate the same thing internally and would be even simpler (you'll be able to keep your code referring to root
as is).
Alternatively, you can just return the value of the new head pointer from the function. This would limit you to a single return value though (which is fine in this case)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.