Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#include <cstdlib>
#include <iostream>

int main(int argc, char *argv[])
{
   cout << "size of String " << sizeof( string );
        
   system("PAUSE");
   return EXIT_SUCCESS;
}

Output:

size of String = 4

Does that mean that, since sizeof(char) = 1 Byte (0 to 255), string can only hold 4 characters?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
103 views
Welcome To Ask or Share your Answers For Others

1 Answer

It isn't clear from your example what 'string' is. If you have:

#include <string>
using namespace std;

then string is std::string, and sizeof(std::string) gives you the size of the class instance and its data members, not the length of the string. To get that, use:

string s;
cout << s.size();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...