為什麼SIZEOF(STR.SUBSTR(0,3).C_STR())=8?

來源:互聯網
上載者:User

譯自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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.