gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:49:00 30 4
gpt4 key购买 nike

我在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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com