Home > Enterprise >  linked list not inserting new values "C language"
linked list not inserting new values "C language"

Time:11-28

I'm running into an issue where my linked list is not adding the new values I give it.. it's resulting in a segmentation fault but I am lost on how to fix it

Current Code

typedef struct node {
  int value;/*data stored in the node  */
  struct node *next;
 /*pointer to the next node*/
} NODE;

void add(NODE **list, int n){//add_to_list in slides
  NODE *new_node;

  new_node = malloc(sizeof(NODE));
  if (new_node == NULL) {
    fprintf(stderr,"Error:malloc failed in add_to_front \n");
    exit(EXIT_FAILURE);
  }
  new_node->value = n;
  new_node->next = *list;
  //return new_node;

}
void print_list(NODE *list){
  printf("\n=========\n");
  for (;list;list=list->next){
    printf("%d\t",list->value);
  }
  printf("\n=========\n");
  }

int main()
{
  NODE *first=NULL;
 
  print_list(first);
  add(&first,10);
  add(&first,30);
  add(&first,20);
  add(&first,40);
  add(&first,30);
  print_list(first);

}

Update

I added in main but now instead of the segmentation fault nothing prints...

add(&first, number)

The fault happens in the add function, more specifically this line "new_node->next = *list;"

I tried dereferencing and many other things, to no avail.

CodePudding user response:

The node is not inserted because you do not update the head pointer: add this statement at the end of the add() function:

        *list = new_node;

CodePudding user response:

make the changes to the dereferenced list

(*list) = new_node;

in order to add the new_node values into the list.

  • Related