2015-02-24 40 views
0

的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」內存,當我得到一個錯誤。爲什麼它給我這個錯誤,我該如何解決它?謝謝

回答

1

你快到了,但是你的createStudentList函數有一些問題。首先,檢查這一行的括號:

studentList[i]->name = new char[strlen(names[i]+1)]; 

它並不完全符合你的要求。

接下來,想想這行真的這樣做,

studentList[i]->name = names[i]; 

你試圖使字符串的副本(你必須是,看到你爲它分配內存)?如果是這樣,請再想一想這條線。

+0

我覺得我應該做'* 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

+0

c樣式的字符串是一個字符數組,你不能像這樣複製它。請參閱[cstring頭文件](http://en.cppreference.com/w/cpp/header/cstring)瞭解可用函數。 – Anthony 2015-02-24 04:57:20

+0

試着拉開你的'新'陳述。 'name [i] + 1'會給出什麼?隨後,'strlen(名字[i] + 1)'給了什麼?可能不是你所期待的。 – Anthony 2015-02-24 04:59:02

2

createStudentList

... 
studentList[i]->name = new char[strlen(names[i]+1)]; 
studentList[i]->name = names[i]; 
... 

哎喲!您分配內存,然後放棄它並將name指針設置爲指向屬於參數names的內容。當你需要時,你不應該期望這個東西仍然存在,並且根據你的錯誤信息判斷它已經超出了範圍或者被刪除了。