c++ - 删除后指针未设置为 nullptr

标签 c++ pointers

我在destroyStudent()函数中删除指针aStudent,然后我将aStudent设置为空指针。但是,运行该函数后,aStudent 不再设置为nullptr,所以我必须再次将其设置为nullptr

#include <cstring>

using namespace std;

struct Student {
   char *     name;
   float      gpa;
};

Student * createStudent(const char name[], float gpa) {
    struct Student * student = new Student;
    student->name = (char*)malloc(strlen(name + 1)); //allocate only enough memory to fit the given name
    strcpy(student->name, name);
    student->gpa = gpa;

    return student;
}

bool destroyStudent(Student * aStudent) {
    if(aStudent) { //check whether this pointer is already null.
        free(aStudent->name);
        delete aStudent; // ******This is where the issue is******
        aStudent = nullptr;
        return true;
    }
    return false; //aStudent is already null
}


int main() {
    Student * student1 = createStudent("Charles", 2.5);
    cout << student1->name << " and " << student1->gpa << endl;
    destroyStudent(student1);
    if(student1) {
        cout << "Pointer is NOT null!!!" << endl;
        student1 = nullptr;
    }

    if(!student1) {
        cout << "The pointer is null now." << endl;
    }

    return 0;
}

最佳答案

问题是 aStudent 是指针的本地拷贝。

您需要像这样通过引用传递指针:

bool destroyStudent(Student*& aStudent) {
    if(aStudent) { //check whether this pointer is already null.
        free(aStudent->name);
        delete aStudent; // ******This is where the issue is******
        aStudent = nullptr;
        return true;
    }
    return false; //aStudent is already null
}

这样,您更改的是外部指针,而不是本地拷贝。

关于c++ - 删除后指针未设置为 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30146267/

相关文章:

c++ - std::list 反向迭代和删除导致崩溃

C++ 指针——奇怪的循环行为

C++ 对象指针改变位置

c++ - 将 bool 数组视为二进制递增

c++ - 使用 IMediaSeeking 检测视频结尾

C++ STL 优先队列排序不正确

c# - 为什么 *(int*)0=0 不会导致访问冲突?

java - 使用Parse.com指针查询两个类的数据,指针值异常

c++ - 如何将对象传递给 C++ 中的函数?

c++ - vector 超出范围/范围检查