c++string

What does sizeof(string) mean?


#include <cstdlib>
#include <iostream>

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

Output is

size of String = 4

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


Solution

  • 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();