0

I am having trouble appending nodes to my linked list when the link list is NULL. In main it always prints NIL. How do I fix this. Here is my implementation of linked list node, and the create node and append node functions.

struct LL_node {
    int data;
    struct LL_node* next;
  };
  typedef struct LL_node LL_node_t;

LL_node_t* create_node(int x){
  LL_node_t* node = (LL_node_t*)malloc(sizeof(LL_node_t)) ;
  node->data = x;
  node->next = NULL;
  return node;
}

void append_node(LL_node_t* start,int x){
  LL_node_t* node = create_node(x);
  if(start == NULL){
    start = node;
    return;
  }
  LL_node_t* nodes =  start;
  while(nodes->next != NULL){
    nodes =  nodes->next;
  }
  node->next = create_node(x);
}

int main(void) {
  LL_node_t* head = create_node(5);
  LL_node_t* nodes = NULL;
  append_node(nodes,3);
  printf("%p\n",nodes);
  return 0;
}
RS123
  • 45
  • 3
  • What do you want to print with `printf("%p\n",nodes);`? – anotherOne Dec 11 '20 at 23:25
  • 1
    `void append_node(LL_node_t* start,int x)` This passes the `start` pointer by value. `start = node;` This modifies the *copy* of the pointer received as an argument. It does not, and cannot, modify the value of the original pointer `nodes` in `main`. – dxiv Dec 11 '20 at 23:26

1 Answers1

1

C is strictly call by value. When you pass nodes to append_node, inside the function you will have a copy of the pointer value. The modified value will not be passed back to the caller.

You have two options:

  1. Return the modified value and assign it in the calling function (main) or
  2. pass the address of the pointer to be able to modify the pointer in the called function (append_node).

First variant:

LL_node_t* append_node(LL_node_t* start,int x){
  LL_node_t* node = create_node(x);
  if(start == NULL){
    start = node;
    return start;
  }
  LL_node_t* nodes =  start;
  while(nodes->next != NULL){
    nodes =  nodes->next;
  }
  node->next = create_node(x);
  return start;
}

int main(void) {
  LL_node_t* head = create_node(5);
  LL_node_t* nodes = NULL;
  nodes = append_node(nodes,3);
  printf("%p\n",nodes);
  return 0;
}

Second variant:

void append_node(LL_node_t** start,int x){
  /* avoid dereferencing NULL pointer */
  if(start == NULL) {
    return;
  }
  LL_node_t* node = create_node(x);
  if(*start == NULL){
    *start = node;
    return;
  }
  LL_node_t* nodes =  *start;
  while(nodes->next != NULL){
    nodes =  nodes->next;
  }
  node->next = create_node(x);
}

int main(void) {
  LL_node_t* head = create_node(5);
  LL_node_t* nodes = NULL;
  append_node(&nodes,3);
  printf("%p\n",nodes);
  return 0;
}
Bodo
  • 9,287
  • 1
  • 13
  • 29