的dellete數組:分配並給予下述的結構聲明指針
struct Student
{
char * name;
float gpa;
}
實現以下功能:
Student ** createStudentList(char ** names, int size);
上述函數創建指針數組到學生動態對象。它分配Student對象並將其名稱設置爲傳入的「名稱」,gpa爲0.「size」是可用「名稱」的數量。該函數返回指向Student指針數組的指針。
bool destroyStudentList(Student ** studentList, int size);
上面的函數刪除數組中所有的Student對象及其動態分配的數據成員,如名稱。它還釋放指向Student對象的指針數組。如果操作成功,則函數返回true,如果「studentList」包含nullptr,則返回false。
這裏是我的功能:
Student ** createStudentList(char ** names, int size){
Student **studentList;
studentList = new Student*[size];
for (int i = 0; i < size; i++) {
studentList[i] = new Student;
studentList[i]->name = new char[strlen(names[i]+1)];
studentList[i]->name = names[i];
studentList[i]->gpa = 0;
}
return studentList;
}
bool destroyStudentList(Student ** studentList, int size) {
if (studentList = NULL)
return false;
else {
for (int i = 0; i < size; i++) {
delete [] studentList[i]->name;
studentList[i]->name = nullptr;
delete studentList[i];
studentList[i] = nullptr;
}
delete[] studentList;
return true;
}
}
它看起來像功能createStudentList
工作正常,但試圖解除分配爲delete [] studentList[i]->name;
「訪問衝突閱讀位置00000000」內存,當我得到一個錯誤。爲什麼它給我這個錯誤,我該如何解決它?謝謝
我覺得我應該做'* studentList [i] - > name = * names [i];'而不是'studentList [i] - > name = names [i];'。但是我不明白'studentList [i] - > name = new char [strlen(names [i] +1)]的括號錯誤在哪兒;' – ReeSSult 2015-02-24 04:53:06
c樣式的字符串是一個字符數組,你不能像這樣複製它。請參閱[cstring頭文件](http://en.cppreference.com/w/cpp/header/cstring)瞭解可用函數。 – Anthony 2015-02-24 04:57:20
試着拉開你的'新'陳述。 'name [i] + 1'會給出什麼?隨後,'strlen(名字[i] + 1)'給了什麼?可能不是你所期待的。 – Anthony 2015-02-24 04:59:02