2014-03-03 43 views
0

嘗試將字符串添加到動態數組時,出現「EXC_BAD_ACCESS」錯誤。難道我做錯了什麼?下面是一些代碼片段:無法將字符串分配給動態數組位置

typedef unsigned short ushort_t; 
typedef string* stringPtr_t; 

class Doctor { 
private: 
    string doctorName; 
    stringPtr_t patientArray; 
    ushort_t patientArraySize; 
    ushort_t numOfPatient;  

    bool Doctor::addPatient(string patientName) 
    { 
     patientArray[numOfPatient].assign(patientName); 
     numOfPatient++; 
     return true; 
    } 

    Doctor& Doctor::operator =(const Doctor& docSource) 
    { 
     for (int i = 0; i < docSource.patientArraySize; i++) { 
      patientArray[i].assign(docSource.patientArray[i]); 
     } 
     return *this; 
    } 
}; 

int main() 
{ 
    Doctor testDoc5(2); 
    cout.clear(); 
    assert(testDoc5.addPatient("Bob Smith")==true); 
} 

Doctor::Doctor(ushort_t patientArrayCapacity) 
    : doctorName("need a name.") 
    , patientArraySize(patientArrayCapacity) 
    , numOfPatient(0) 
{ 
    patientArray = *new stringPtr_t[patientArraySize]; 
} 
+1

patientArray分配給了哪裏? – Mark

+1

您是否爲patientArray分配了任何內存? – veda

+0

@Mark將其分配給先前構造的醫生對象,我將編輯以顯示此內容。 – user3373291

回答

0

犯罪嫌疑人行:

patientArray = *new stringPtr_t[patientArraySize]; 

讓我們來看看這更詳細一點。

展開(取代的typedef)導致

patientArray = * new string * [patientArraySize]; 

綜觀分配部分:

new string * [patientArraySize]; 

中分配指針數組爲字符串。這可能不是你想要的。

下一部分:

* (new string * [patientArraySize]); 

取消引用指針字符串數組,從而指的是陣列的第一個元素。

最後,分配:

patientArray = * (new string * [patientArraySize]); 

分配陣列位置零的內容,您的變量patientArray。這是合法的,因爲你告訴編譯器你將指針分配給字符串。

副作用:
1.您已經丟失了陣列的開始位置。也稱爲內存泄漏。
2. patientArray指針的內容未定義,因爲您沒有在數組的第一個位置初始化指針值。

也許你想:

patientArray = new string [patientArraySize]; 

其中分配字符串數組,並分配到相應的指針patientArray

如果您使用std::vector<string>(patientArraySize),則整個問題將消失。

相關問題