为什么sizeof(str.substr(0,3).c_str())给我8?

use*_*343 1 c++ string

string str = "abcdefgdcb";

cout << sizeof(str.substr(0,3).c_str());
Run Code Online (Sandbox Code Playgroud)

出于某种原因,上面的字符串给了我8.我假设c_str()返回一个空字符串,而sizeof使用null来确定字符串的大小.

Oli*_*rth 9

因为sizeof没有给出字符串的长度,所以它给出了类型的大小(const char *在这种情况下).试试strlen.