删除后指针未设置为nullptr

时间:2015-05-09 23:51:36

标签: c++ pointers

aStudent destroyStudent()函数中的指针aStudent,然后我将nullptr设置为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; }

import Foundation

class RecordedAudio: NSObject{
    var filePathUrl: NSURL!
    var title: String!
}

2 个答案:

答案 0 :(得分:6)

问题是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
}

这样就是你改变的外部指针,而不是本地副本。

答案 1 :(得分:0)

C ++使用pass-by-value

您要将destroyStudent()方法的本地变量设置为nullptr,而不是main()中的变量。