看看這段代碼:我試圖從控制檯讀取一些字符串,並將它們存儲在一個動態數組中。C++指向字符串數組的指針
int Doctor::addPatients()
{
string* names = NULL;
int num;
cout << "how many patients are to be added? ";
cin >> num;
numPatients=num;
names = new string[numPatients];
for(int i=0;i++;i<numPatients){
cout << "enter the next patient's name: ";
cin.clear();
cin >> names[i];
}
patients = names; //patients is a private member variable of class Doctor
}
當我執行這個代碼,我得到以下錯誤:
malloc: *** error for object 0x10c100898: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
任何幫助是極大的讚賞
停止使用指針,改爲['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –