Passing a pointer is basically like passing a pointer as value.. the changes to the pointer internally in the function will not modify the actual value of the pointer.. but when we need to access on the actual pointer itself in a function, then we are coming up with the pointer to pointer concept. this is my understanding..
struct node
{
int data;
struct node* next;
};
void push(struct node** head_ref, int new_data) // i understand the need of pointer to pointer here, since we are changing the actual value by adding a node..
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void insertAfter(struct node* prev_node, int new_data) // why are we not using pointer to pointer here since even here the pointer data is getting modified..??
{
if (prev_node == NULL)
{
return;
}
struct node* new_node =(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
int main()
{
struct node* head = NULL;
append(&head, 6);
insertAfter(head->next, 8);
return 0;
}
Please clarify.. i'm confused why we are not using pointer to pointer in InsertAfter(...) as well thought we change the pointer there?
The difference is what the functions do with what you pass in.
This modifies what *head_ref
itself points to:
void push(node** head_ref, int new_data);
While this modifies the contents of the node
that prev_node
points to - but it still will end up pointing to the same node
:
void insertAfter(node* prev_node, int new_data);
Looking at actual usage clears this up too:
// head points to the node 0
node* head = new head{0, nullptr};
// head now points to the node 5, which itself points to the node 0
// so our list is {5} --> {0}
push(&head, 5);
^
additional clue that we are modifying head
// head->next points to the node 0 before this
// it **still** continues to point to that node after the call, but we
// change what comes after it, to now be a new node 3
// so our list is {5} --> {0} --> {3}
insertAfter(head->next, 3);
// head is still the 5. head->next is still the 0.