Reputation: 1427
I was writing code on Doubly Linked List for the following function
struct node {
int data;
struct node *next;
struct node *prev;
};
/* Given a node as next_node, insert a new node before the given node */
void insertBefore(struct node** next_node, int new_data)
I called the insertBefore() from the main function:
insertBefore(&head, 2); // it works fine
But i can't do the same fore head->next, because next pointer is just node* Not node**
insertBefore(head->(&next), 2); // it doesn't works
How can i solve the problem.please help.Thanks
Upvotes: 0
Views: 4043
Reputation:
Change your function to take a reference to the node pointer.
void insertBefore(node*& next_node, int new_data);
...
insertBefore(head->next, 2);
Upvotes: 1
Reputation: 7887
It seems illogical to dereference a pointer than reference its address...
&(head->next)
will work but it works because you dereference the pointer (grab the value that the pointer points to) than grab the address of that pointer again using &
.
->
is the same as .(*next)
. The arrow is just the easiest way to get what the pointer points to. If you want the value of the pointer itself all you have to do is head.next
.
Upvotes: 0
Reputation: 2259
head
is a pointer in case of insertBefore(&head, 2);
next
is also a pointer and a member of struct node
.
So, if you want to access next
via head
(i.e pointer to some node) then,
syntax would be head->next
. Now you can get address of next
by &(head->next)
.
Upvotes: 1
Reputation: 77304
Assuming your function works, &(head->next)
is what you need.
insertBefore(&(head->next), 2);
Upvotes: 1