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