譯自stackoverflow,一個很有意思的問題。
問題:
string str = "abcdefgdcb";cout < < sizeof(str.substr(0,3).c_str());
For some reason, the above string is giving me 8. I assumed c_str() returns a null string,
由於某些原因,上面的這個字串得到的結果是8,我估計c_str()返回了一個null,
and sizeof uses the null to determine the size of the string.
並且sizeof函數使用這個null來定義這個字串的大小。
答案:
Because sizeof doesn’t give you the length of a string,
因為sizeof給你的不是一個字串的長度,
it gives you the size of the type (const char * in this case). Try strlen.
他給你的是這個類型的大小(這種情況下的類型是c_str()返回的const char*類型),想要得到正確的結果,試試strlen函數吧。
On your system, sizeof (const char *) == 8, like any other pointer.
在你的系統上,sizeof(const char*)=8,和其他所有的指標類型一樣。
8 is the size of a pointer on your machine (64-bit)
8是在你的64位電腦上一個指標的大小
There’s your problem. sizeof tells you the size of a variable,
別亂假設,sizeof告訴你一個變數的大小,
which has nothing to do with the value inside the variable, ever.
他不會進入變數裡面對變數做任何改變的。。永遠不會。
問題:http://stackoverflow.com/q/10668764/764869