Hello,
I'm trying to understand the logic of recursive structures (or is "linked list" much proper term?) and I have a problem with following code:
I was hoping it prints out all six of the names, but the actual outpot is:Code:#include <stdio.h> #include <stdlib.h> struct person { const char *first_name; const char *last_name; int age; struct person *next; }; typedef struct person PERSON; void add_new_person(PERSON **p_obj, const char *first_name, const char *last_name, int age) { PERSON *p = (PERSON *)malloc(sizeof(PERSON)); p = *p_obj; if(p->next != NULL) p = p->next; p->first_name = first_name; p->last_name = last_name; p->age = age; p->next = (PERSON *)malloc(sizeof(PERSON)); return; } void show_persons(PERSON **p_obj) { PERSON *p = (PERSON *)malloc(sizeof(PERSON)); p = *p_obj; if(p != NULL) { while(p->next != NULL) { printf("%s %s (age: %d years)\n" , p->first_name , p->last_name , p->age ); p = p->next; } } return; } int main(void) { PERSON *nice_person = (PERSON *)malloc(sizeof(PERSON)); add_new_person(&nice_person, "Donald", "Duck", 122); add_new_person(&nice_person, "Jack", "Sparrows", 32); add_new_person(&nice_person, "Bruce", "Wayne", 40); add_new_person(&nice_person, "Gregory", "House", 55); add_new_person(&nice_person, "Luke", "Skywalker", 20); add_new_person(&nice_person, "Hannibal", "Lecter", 65); show_persons(&nice_person); return 0; }
(the first and the last item from the list).Code:Donald Duck (age: 122 years) Hannibal Lecter (age: 65 years)
I can't figure out what am I doing wrong here.



1Likes
LinkBack URL
About LinkBacks



