简体   繁体   中英

Delete dynamically allocated array c++

bool StudentList::remove(const char * studentName)
{
    for (int i = 0; i < MAX_SIZE; i++)
    {
        if (this->students[i]->isEqualTo(studentName)) // Finds a name to remove
        {
            cout << "Remove: "; // Displays name wished to be removed
            students[i]->print();
            // delete[] students[i]; - Crashes 
            // students[i] = NULL; - Replaces removed name with null, stops working.  
            // students[i]->~Student(); - Call deconstructor, Crashes.
            return true;
        }
    }
    return false;
}

I just want to remove a single element out of the array, but keeps crashing when i delete that element.

students[i] is a pointer array, and i need to remove selected elements

It seems that you want to delete each instance of students, if you could find the studentname.

students seems a two dimensional structure pointer to a pointer. ie; **students . But, you are deleting it in wrong way.As you first need to delete the instance of students[i] , then delete the instance of students.

Also, since you are calling the destructor students[i]->~Student(); after deleting instance, it may crash again, as you have assigned student[i] = NULL . then it will be, NULL->~Student() -it will also lead crash.

You need to delete it in following way :

for (int i = 0; i < MAX_SIZE; i++)
{
    if (this->students[i]->isEqualTo(studentName)) // Finds a name to remove
    {
        students[i]->~Student();

        delete students[i];

        students[i] = NULL; 
    }
 }
 delete[] students;

 students = NULL; 

First quetion, if you really need to delete "Student" object. If yes, you can add some bad code like:

students[i] = nullptr;

If your students are stored not only in this array, you can make that storage responsible for their deleting. But both ways aren't very good because of using null pointers later. Learn how to use collections, for example vector . You will be able just remove the pointer from an array.

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