2012-05-11 33 views
0

這只是一個基本的打印句子數組字符串。我是新來的C++只使用JAVA和類似的語言從來沒有C以前。嘗試通過檢查每種不同的排序算法和數據結構來學習它。C++ sizeof給出一個錯誤未處理的異常在

但在我開始之前,只是測試我的字符串數組會給我一個錯誤。我不知道爲什麼它給了我一個錯誤。在實際運行中編譯並打印intend內容,但如果正在調試,則會崩潰並顯示錯誤。任何人都可以向我解釋爲什麼是這樣。試圖size()length()從C++庫,但不得不使用sizeof() '

//BubbleSort.cpp 
#include "stdafx.h" 
#include <string> 
#include <iostream> 
using namespace std; 

int main() 
{ 
    string something[14]; 
    something[0] = "Kate"; 
    something[1] = "likes"; 
    something[2] = "lots"; 
    something[3] = "of"; 
    something[4] = "cake"; 
    something[5] = "in"; 
    something[6] = "her"; 
    something[7] = "mouth"; 
    something[8] = "and"; 
    something[9] = "will"; 
    something[10] = "pay"; 
    something[11] = "a"; 
    something[12] = "lot"; 
    something[13] = "lol"; 
    int some = sizeof(something); 
    some--; 
    for (int i = 0; i < some; i++) 
    { 
     cout << something[i] << " " ; 
    } 
    system("pause"); 
    return 0; 
} 
+4

你應該考慮使用'std :: vector'或'std :: deque'。 –

回答

8

sizeof(something)像您期望不會再回到14,但它返回sizeof(string)*14所以你當您嘗試打印遇到一個緩衝區溢出。 你需要的是

some = sizeof(something)/sizeof(string) 

或由@Tiago提到你可以使用

some = sizeof(something)/sizeof(something[0])

另外,作爲@詹姆斯建議你應該看看std:vector

+1

你也可以這樣做:sizeof(something)/ sizeof(* something) –

+0

@TiagoPeczenyj謝謝編輯答案 – keety

+1

@TiagoPeczenyj如果'something'是一個數組 – Ulterior