why is sizeof(str.substr(0,3).c_str()) giving me 8?

c++, string

Solution

Because `sizeof` doesn't give you the length of a string, it gives you the size of the type (`const char *` in this case). Try `strlen`.

Problem

``` 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, and sizeof uses the null to determine the size of the string.

Original source