Kevin Meredith Kevin Meredith - 2 months ago 25
C++ Question

c++ sizeof( ... )

#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?

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