2013-03-23 251 views
3

評論公正地解釋了這一切。幫幫我?字符串矩陣的sizeof

string aZOM[][2] = {{"MoraDoraKora", "PleaseWorkFFS"},{"This is a nother strang.", "Orly?"}}; 
cout << sizeof("MoraDoraKora") <<" \n"; 
//Obviously displayes the size of this string... 
cout << sizeof(aZOM[0][0]) << " \n"; 
//here's the problem, it won't display the size of the actual string... erm, what? 

string example = aZOM[0][0]; 
cout << example << " \n"; 
cout << aZOM[0][1] << " \n"; 
//Both functions display the string just fine, but the size of referencing the matrix is the hassle. 

回答

4

sizeof給你,你傳遞給它以字節爲單位的對象的大小。如果你給它一個std::string,它會給你std::string對象本身的大小。現在,我的對象爲實際字符動態分配存儲空間,幷包含一個指向它們的指針,但這不是對象本身的一部分。

要獲得std::string的大小,使用其size/length成員函數:

cout << aZOM[0][1].size() << " \n"; 

sizeof("MoraDoraKora")正常工作的原因是因爲字符串文字"MoraDoraKora"一個std::string對象。它的類型是「13 constchar1陣列」等sizeof報告以字節數組的大小。

+0

注意;對於第一個你得到一個const char *的大小? – Skeen 2013-03-23 00:30:34

+0

這似乎是更好的解釋。 :) – scones 2013-03-23 00:31:18

+0

@Skeen你得到數組的大小,因爲數組不會經歷數組到指針的轉換作爲'sizeof'的操作數。 – 2013-03-23 00:31:48

2
sizeof

返回類型的大小,而不是數據的大小指向。

一個字符串,通常是一個字符指針,在生產鏈的最後一個字符的值爲0

如果你想字符串的實際大小,你可以使用aZOM[0][0].length()