Why is sizeof (Str. substr (0, 3). c_str () = 8?

Source: Internet
Author: User

Translated from stackoverflow, an interesting question.

Problem:

 
StringSTR ="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,
For some reason, the result of the above string is 8. I estimate that c_str () returns a null value,

And sizeof uses the null to determine the size of the string.
And the sizeof function uses this null to define the size of this string.

Answer:
Because sizeof doesn't give you the length of a string,
Because sizeof does not give you the length of a string,

It gives you the size of the type (const char * in this case). Try strlen.
He gave you the size of this type (in this case, the type is the const char * type returned by c_str (). To get the correct result, try the strlen function.

On your system, sizeof (const char *) = 8, like any other pointer.
In your system, sizeof (const char *) = 8, the same as all other pointer types.

8 is the size of a pointer on your machine (64-bit)
8 is the size of a pointer on your 64-bit computer

There's your problem. sizeof tells you the size of a variable,
Do not assume that sizeof tells you the size of a variable,

Which has nothing to do with the value inside the variable, ever.
He will not make any changes to the variable in the variable .. Never.

Problem: http://stackoverflow.com/q/10668764/764869

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.