+ 5

C linked list pointer

I got this code from my cs script and dont understand why Person **anchor in line 20 is a double pointer: void add_first(Person **anchor, Person *person) code: #include <stdio.h> typedef struct Person { char name[10]; int alter; struct Person *next; } Person; Person *create(char *person_name, int person_alter) { Person *neu = ( Person *)malloc( sizeof(Person) ); if ( neu == NULL ) return NULL; strncpy( neu->name, person_name, 9 ); neu->alter = person_alter; return neu; } // but why? void add_first(Person **anchor, Person *person) { person->next = *anchor; *anchor = person; } int main() { Person *liste = NULL; add_first( &liste, create("Max", 18) ); add_first( &liste, create("Lisa", 21) ); add_first( &liste, create("Fritz", 19) ); Person *element = liste; while( element != NULL ) { printf("%-10s (%d Jahre)\n", element->name, element->alter); element = element->next; } return 0; }

15th Jun 2019, 11:18 AM
Maxim Schiffmann
Maxim Schiffmann - avatar
2 Réponses
+ 7
The add_first() function always adds the new element to the start of the list rather than the end. This means that the anchor or the pointer to the first element always needs to be modified. If you're modifying a pointer within a function, you needs double indirection or the need to pass in the address of the pointer.
15th Jun 2019, 12:58 PM
Sonic
Sonic - avatar
+ 6
Btw, there's a bug in this program. Without stdlib.h, the malloc() function implicitly returns an int (not a void *) and the typecast to (Person *) will likely mask any compiler warnings. I'd advice against casting the return type of malloc() since void * is automatically promoted to the correct type. You're also leaking memory. So to free the list, go through each element and have a temp variable hold the current list entry. Go the next list entry and then free the temp variable (which holds the previous entry).
15th Jun 2019, 1:40 PM
Cluck'n'Coder
Cluck'n'Coder - avatar