Reputation: 43
I've got a console application reading some char-data from the console and then puts in into a structure. This structure is used as linked list, when it's constructed, I keep one pointer pointing to the first list element and one pointer for running through the list. What happens to me is, when I first run through my list and write its contents into the console, everything works perferctly. When I later want to set my running pointer to the lists last element, it keeps crashing with an c000005 access violation error. I will give you the interesting parts of my code:
definition of my structure:
struct musikdaten {
char interpret[150];
char titel[150];
struct musikdaten* next;
};
printing the lists content:
while (it != NULL) {
cout << it->interpret << ": " << it->titel << "\n";
cout << "next: " << it->next << "\n";
it = it->next;
}
setting "it" to the lists last element:
while (true) {
if (it->next == NULL) {
cout << "Assigning some memory...\n";
it->next = new musikdaten;
break;
}
else it = it->next;
}
However, this last part keeps crashing when the list contains more than two elements. Note: When a new list element is added while reading it's content from console, the next pointer is always initialized as NULL.
Upvotes: 0
Views: 122
Reputation: 23324
You should initialize the next
member with NULL
to indicate the end of the list:
it->next = new musikdaten;
it->next->next = NULL;
Or add a default constructor:
struct musikdaten {
musikdaten() { next = NULL; /*TODO: init other members*/}
char interpret[150];
char titel[150];
struct musikdaten* next;
};
Upvotes: 2