2016-12-29 55 views
0

如何解決這個錯誤,當我運行和關閉這個項目? 我寫了一個C++程序,它有這個錯誤: 觸發了一個斷點。C++錯誤:<project_name>觸發了一個斷點

int num = 0; 
string **board = new string*[num]; 

cin >> num; 
system("cls"); 
for (int i = 0; i < num; i++) 
    board[i] = new string[num]; 

for (int i = 0; i < num; i++) 
    for (int j = 0; j < num; j++) 
     board[i][j]='_'; 


for (int i = 0; i < num; i++) 
{ 
    if(i!=0) 
    cout << endl<< endl<<endl<< endl; 
    for (int j = 0; j < num; j++) 
     cout << board[i][j]<<"    "; 
} 




cin.get(); 
cin.get(); 
for (int i = 0; i < num; i++) 
    delete[] board[i]; 
delete[] board; 
return 0; 
+0

你能發佈確切的錯誤嗎? – Danieboy

+0

觸發了一個斷點。 –

+0

wntdll.pdb不包括 –

回答

2

聲明

string **board = new string*[num];

需要被定位後你cin >> num;閱讀。

否則你試圖分配一個零長度的指針數組;這在C++中沒有很好的定義。

繼續前進,您可能會發現將整個板作爲單個std::vector<std::string>進行建模會更簡單,這將大大簡化內存管理。

+0

非常感謝你 –

1
int num = 0; 
cin >> num; 
string *board = new string[num]; // here 
system("cls"); 
for (int i = 0; i < num; i++) 
    board[i] = string(n,'_'); 
for (int i = 0; i < num; i++) 
{ 
    if(i!=0) 
    cout << endl<< endl<<endl<< endl; 
    for (int j = 0; j < num; j++) 
     cout << board[i][j]<<"    "; 
} 
cin.get(); 
cin.get(); 

delete[] board; 
return 0; 

Strings and containers allocate/deallocate automatically. However, a container of pointers doesn't free up what those pointers point to. We have to loop through those to free them.

我剛纔簡單的代碼位。

+0

我改變了它 tnx –

+0

你不應該刪除「內部刪除」嗎? – Bathsheba

+0

@Bathsheba .: yike yes..for字符串它的neing自動調用每個對象.. – coderredoc

相關問題