sara McKnight
sara McKnight

Reputation: 21

Linked List, pointer manipulation

I am attaching below the code of head_insert to insert a new node at the head of a linked list. The function is called with head_insert(head).

I am not sure about the syntax of the first argument of the function, I was expecting NodePtr instead since it is already a pointer, see below.

Why the code uses NodePtr &head and not NodePtr head only as head is already a pointer?

void head_insert(NodePtr & head, int the_number)
{
  NodePtr temp_ptr;
  temp_ptr=new Node;
  temp_ptr->data=the_number;
  temp_ptr->link=head;
  head=temp_ptr;
}


struct Node
{
  int data;
  Node *link;
};

typedef Node* NodePtr;

Upvotes: 2

Views: 354

Answers (2)

Rerito
Rerito

Reputation: 6086

Your typedef is a little confusing at first glance. In C, you should pass a struct Node ** head argument and assign its value to the newly created node : *head = temp_ptr;. Here is what it would look like :

void head_insert(struct Node **head, int the number)
{
    struct Node *new_head = NULL;
    // Alloc memory for new_head, etc..
    new_head->data = the_number;
    new_head->link = *head;
    *head = new_head;
}

Thus, to make the assignment *head = new_head, you need to have a pointer to your list head which is also a pointer. Otherwise, the update performed in the function would remain local. In your code, you take a reference to a pointer, which has merely the same effect than passing a "double" pointer.

Upvotes: 0

NPE
NPE

Reputation: 500257

why the code uses "NodePtr &head" and not "NodePtr head" only as head is already a pointer?

The reason is that it needs any changes that the function makes to head to be visible to the caller.

If head were passed by value (NodePtr head) rather than by reference (NodePtr& head) this wouldn't be the case: when the function would assign temp_ptr to head, this change wouldn't propagate back to the caller. Passing head by reference addresses this.

Upvotes: 4

Related Questions