-1

I just started working with linked lists and structures and am very new to coding. The following code is a function that when called adds a new dog to the structure of dogs. I don't get a segmentation fault when entering the first dog but only when I enter another dog do I get this issue. I'm not sure how to fix this so any help would be much appreciated.

    if(list == NULL){
            list = new_node;
            return list;
    }

    while(p->next != NULL){
            p = p->next;
    }
    p->next = new_node;
    return list;
 }
YellowBird
  • 25
  • 5

2 Answers2

1

You just need to initialize p before entering the while loop at the bottom:

p = list;
while (p->next != NULL) {
    p = p->next;
}

On an unrelated note, earlier in the function, when checking for a duplicate patient number, you probably want to change the break; to a return list; Otherwise it will just exit the loop and continue adding a new node to the list.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

You need to reset p here. At this point it is null and you dereferencing it.

p = list; // add this

while(p->next != NULL)
{ 
    p = p->next; 
} 
p->next = new_node; 
return list; 
Pemdas
  • 543
  • 2
  • 9