I delete
указатель aStudent
в функции destroyStudent()
, затем я установил aStudent
в nullptr
. Однако после запуска функции aStudent
больше не установлен на nullptr
, поэтому я должен снова установить его на 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;
}
Вы устанавливаете копию указателя. Объект удаляется, но копия указателя устанавливается равным null, а не оригиналу. – phantom
@Phantom Возможно, вы должны добавить это как ответ – Sinkingpoint
В 'destroyStudent' вы проходите Student * по значению. Возможно, вам нужен 'bool destroyStudent (Student * & aStudent)' – drescherjm