infinite infinite - 9 months ago 58
C++ Question

Different size of string showing when going by two different methods

when I go by this:

string s="hello";

Then it shows 4 as the answer, but when I go for some individual value:

string s="hello";

It shows 1 as output. Going by this output the answer of 1st should be 5 as there are five characters in the string. Where am I wrong? (I ran this on Ideone).

Answer Source

sizeof() returns the compile-time byte size of the type of the specified parameter.

The s variable is an instance of the std::string class, so sizeof(s) returns the byte size of the std::string class itself, which is 4 in a 32-bit executable (8 in a 64-bit executable) because the std::string class contains a single data member that is a pointer to the allocated character data. If you want to know how many characters are allocated for the string at run-time, use the std::string::size() method instead. That will return the 5 you are looking for.

s[2] returns a char, so sizeof(s[2]) returns the byte size of the char type, which is 1.