I'm trying to construct a linked list, with nodes containing strings as oppose to integers. Here's what I have so far:
The program runs, but it terminates abnormally right after when I enter the family name. After some basic debugging, I noticed that the problem is apparently from the count() function, but I can't see what's wrong.Code:#include <iostream> using namespace std; class family { private: struct person { char name[20]; person *next; }*head; public: family(); ~family(); void addname(char c[20]); int count(); }; family::family() { head = NULL; } family::~family() { person *temp; if (head == NULL) return; while (head != NULL) { temp = head->next; delete head; head = temp; } } void family::addname(char c[20]) { person *p, *q; if (head == NULL) { head = new person; head->name[20] = c[20]; head->next = NULL; } else { q = head; while (q->next != NULL) { q = q->next; } p = new person; p->name[20] = c[20]; p->next = NULL; q->next = p; } } int family::count() { int counter = 0; person *q; q = head; while (q->next != NULL) { counter++; q = q->next; } return counter; } int main() { char familyname[20]; cout<<"Enter new family: "; cin>>familyname; family familia; cout<<"The "<<familyname<<" family with "<<familia.count()<<" is created."<<endl; return 0; }
Any help is appreciated.