2012-10-03 80 views
0

看看這段代碼:我試圖從控制檯讀取一些字符串,並將它們存儲在一個動態數組中。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 

任何幫助是極大的讚賞

+1

停止使用指針,改爲['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –

回答

3
for(int i=0;i++;i<numPatients) // Condition is the second expression in for syntax 

語法錯誤。

for(int i=0;i<numPatients; i++) 

你使用什麼編譯器?您應該得到比運行時錯誤更多的編譯錯誤。你還寫過一個拷貝構造函數嗎?欲瞭解更多信息,請登錄Rule of Three。爲了緩解這項工作,請使用std::vector<std::string>

+0

我真的搞砸了那個循環。謝謝。其中一件事我甚至沒有考慮再次看(在解決第一個問題之後)。我在Mac OSX上使用g ++,Xcode 4.4.1,調試時除-g之外沒有標誌。 –

3

你不初始化整數i

+0

感謝您的支持。修正了它,錯誤依然存在。 –

+0

我建議的另一件事是使用共享指針。 – ISTB

+0

例如:std :: shared_ptr s(new std :: string()); – ISTB

1

在for語句,for(int i;i++;i<numPatients)

i shoul ð被初始化爲0,條件應該是第二個參數 正確的格式應該是 -

for(int i=0;i<numPatients;i++) 

cin並不好方法來獲得字符串輸入。 CIN只讀取,直到它看到空格(空格,換行,製表..)或者使用getline函數的 -

語法:

getline(cin,names[i]) 
+0

注意您的代碼並添加一些解釋? – Yaroslav

+0

格式不夠好並且沒有說明解釋。 – Mahesh