2014-03-03 41 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),则整个问题将消失。

相关问题