-
Linked list terminates
I'm trying to construct a linked list, with nodes containing strings as oppose to integers. Here's what I have so far:
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;
}
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.
Any help is appreciated.
-
Here is what you do
Code:
head = NULL; //in constructor
p = head; //in count
while(p->next) //crash
in the count - check starting from the current node, not the next node.
PS. You have also issues whith copying the strings in your code, you'll see them when you'll start adding strings... So may be its time to switch to string class
-