简体   繁体   中英

Pointer causes access violation

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.

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM