Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to null struct when passed to function?

I want to NULL the head structure in case the head->next is NULL. However it doesn't work when I pass it into a function to null it.

void remove(struct node* head)
{
 int val;

 cout << "Enter a value to delete: ";
 cin >> val;

 if (head->next == NULL)
  if (head->data == val)
   head = NULL;
}

Though it works fine when not passed to the function, but done directly in the main function. Where do I go wrong?

like image 872
user2180833 Avatar asked Apr 23 '26 10:04

user2180833


2 Answers

The pointer passed as an argument to remove is being copied into the function. The head inside the function is a copy of that pointer. You set that copy to NULL and the one outside is left unchanged. You can simply take the pointer by reference:

void remove(struct node*& head)
{
  // ...
}

Note the ampersand in the type of head. This means it's a "reference to pointer to node" and lets you reference precisely the object that is passed, rather than a copy of it.

like image 73
Joseph Mansfield Avatar answered Apr 25 '26 00:04

Joseph Mansfield


The problem is that you are passing the pointer which lets you modify the node it points to, but you can't modify the pointer itself because the pointer itself is passed by value. So you can't do this in your remove function:

node = NULL;

A solution that people have given you is to pass it as a reference to the pointer, as in node *&head and this works perfectly fine. However I believe you'd like to know that the general convention for this sort of thing (modifying a pointer itself) is by passing a double pointer (i.e. a pointer to the pointer to node):

void remove(node **head) { ... }

Then in main you pass it the address of the pointer:

node *theHead = blah;
remove(&theHead);

Then in remove you can change the value of the pointer:

*head = NULL;

And you can also dereference it of course:

(*head)->next; // etc
like image 42
Jorge Israel Peña Avatar answered Apr 24 '26 23:04

Jorge Israel Peña



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!