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   {     (p = *phead; p->next; p = p->next);     p->next = new;   }   return new; } 

we have singly linked list shown above in functions. node consists of data type int , pointer next node in list. have 2 functions defined. first 1 changes head node, or adds new head node before previous head node. second function adds tail node (the last 1 in list). in main, call them like:

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

now, @ 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 node after argument node. and, in main, if want add node after c1 defined, call function like:

*c3 = add_after(c1, 4); 

my question is: difference between first 2 , third function in terms of arguments. in first 2 functions, have argument **phead , in third function, *node. need **phead, why can't put *phead , in main call like:

node *c1 = add_head(head, 1); 

i hope understood meant, find difficult explain.

  • the address of first element (of type node) contained in pointer (of type node *)

  • the add_head() functions modifies pointer. programming in c, blatantly lacking parameter-passing-by-reference, option transmit address.

so, parameter of type node** (adress of pointer node).

  • for add_after() parameter gives address of node modified. don't have modify address.

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -