A6SE
A6SE

Reputation: 177

C - Singly linked list - passing a pointer by value vs by reference

typedef struct node { int data; struct node *next; } NODE;

NODE* add_head(NODE **phead, int data) {
  NODE *new = (NODE *)malloc(sizeof(NODE));
  new->data = data;
  new->next = *phead;
  *phead = new;
  return new;
}

NODE* add_tail(NODE **phead, int data) {
  NODE *p, *new = (NODE *)malloc(sizeof(NODE));
  new->data = data;
  new->next = 0;
  if (*phead == 0) *phead = new;
  else
  {
    for (p = *phead; p->next; p = p->next);
    p->next = new;
  }
  return new;
}

We have a singly linked list as shown above in the functions. The node consists of the data type int and the pointer to the next node in the list. We have two functions defined. The first one changes the head node, or adds the new head node before the previous head node. The second function adds the tail node (the last one in the list). In the main, we call them like:

NODE *head = 0;
NODE *c1 = add_head(&head, 1);
NODE *c2 = add_tail(&head, 3);

Now, look at this function:

NODE* add_after(NODE *node, int data) {
  NODE *new = (NODE *)malloc(sizeof(NODE));
  new->data = data;

  new->next = node->next;
  node->next = new;

  return new;
}

That function adds a node after the argument node. And, in main, if we want to add a node after c1 previously defined, we call the function like:

*c3 = add_after(c1, 4);

My question is: What is the difference between first two and the third function in terms of the arguments. In first two functions, we have an argument **phead and in the third function, *node. Do we really need **phead, why can't we just put *phead and in the main call it like:

NODE *c1 = add_head(head, 1);

I hope you understood what I meant, I find it difficult to explain.

Upvotes: 0

Views: 1125

Answers (1)

Michel Billaud
Michel Billaud

Reputation: 1826

  • The address of the first element (of type NODE) is contained in a pointer (of type NODE *)

  • the add_head() functions modifies this pointer. As you are programming in C, blatantly lacking parameter-passing-by-reference, your only option is to transmit its address.

So, the parameter is of type NODE** (adress of a pointer to a NODE).

  • for add_after() the parameter gives the address of the NODE to be modified. You don't have to modify that address.

Upvotes: 1

Related Questions