2017-06-23 114 views
0

我使用動態堆分配來創建教室工具來添加學生。程序提示用戶/老師輸入學生姓名,並將其分配給一個數組。堆分配功能命中牆:EXC BAD ACCESS CODE 1

我測試了while循環,它調用add函數負責分配更大的堆陣列。該程序輸出按預期方式添加的學生列表,並可創建更大的堆陣列。

但是,當我嘗試添加第11個學生時,我收到此消息THRD 1 EXC_BAD_ACCESS code1。我讀到這意味着程序無法再訪問內存塊,但是爲什麼這會發生在第11個學生?任何有關調試的建議都非常感謝。感謝您的耐心,我仍然習慣C++

/* 
Dynamic Heap Allocation using pointers 
*/ 
#include <iostream> 
#include <string> 

using namespace std; 

void add(string arr[],int& studs,int& counter){ 
    //copies student names to a bigger array 
    studs+=10; //vs passing by value 
    string* big_brotha = new string[studs]; // a holder 
    for(int i=0;i<counter;i++){ 
     big_brotha[i]=arr[i]; 
    } 
    delete[] arr; 
    arr = big_brotha; 
} 


int main() { 
    int n=5; 
    int count=0; 
    string name; 
    bool cont = true; 
    char option; 
    string* arrayofpointers = new string[n]; 
    cout << "enter student names. Enter Q to quit " << endl; 
    while (cont){ 
     cout << "enter student name for seat number " << count << endl; 
     cin >> name; 
     if (name=="Q"){ 
      for (int i=0;i<count;i++){ 
       cout << arrayofpointers[i] << endl; 
      } 
      break; 
     } 
     cout << "is the counter less than array size? " << (count<n) << endl; 
     if (count>=n){ //time to make the array bigger! 
      cout << "time to make the array bigger!" << endl; 
      add(arrayofpointers,n,count); 
      cout << "the array is now this big " << n << endl; 
      arrayofpointers[count]=name; 


     } 
     else{ 
      arrayofpointers[count]=name; //no longer possible to access memory 
     } 

     count++; 
    } 

    return 0; 
} 

回答

1

在你的情況「arrayofpointers」是複製到您的功能爲「改編」。你刪除它的內容(擺脫它指向的內容),然後爲它分配一個新值。但是,您將值分配給'arr',而不是數組指針。因此,arrayofpointers上的下一個操作將引用已刪除的內存。

你真正需要的是這樣的:

void add(string *&arr,int& studs,int& counter){ 

這將創建一個指針引用。

或該:

void add(string **arr,int& studs,int& counter){ 

這是一個指向指針的指針。

+0

啊我看到了,所以我需要一個指針指針,因爲arr不作爲指針傳遞。在函數調用之後,arrayofpointers被刪除,並且只有五個元素的空間。謝謝! – st4rgut

+0

順便說一句我嘗試了你的建議,並得到了一個錯誤:'arr聲明爲引用數組引用類型的字符串*&'引用指針和'沒有可行的重載='指針指針 – st4rgut

+0

錯誤哪一行?如果使用'**',則必須將指針的地址傳遞給該行:add(&arrayofpointers,n,count);並在這裏使用明星'* arr = big_brotha';如果您使用'*&',它應該按原樣工作。 – Serge