Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ sizeof( string )

Tags:

c++

string

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

like image 328
Kevin Meredith Avatar asked Nov 26 '22 20:11

Kevin Meredith


2 Answers

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();
like image 58
Ori Pessach Avatar answered Nov 29 '22 10:11

Ori Pessach


When string is defined as:

char *string;

sizeof(string) tells you the size of the pointer. 4 bytes (You're on a 32-bit machine.) You've allocated no memory yet to hold text. You want a 10-char string? string = malloc(10); Now string points to a 10-byte buffer you can put characters in.

sizeof(*string) will be 1. The size of what string is pointing to, a char.

If you instead did

char string[10];

sizeof(string) would be 10. It's a 10-char array. sizeof(*string) would be 1 still.

It'd be worth looking up and understanding the __countof macro.

Update: oh, yeah, NOW include the headers :) 'string' is a class whose instances take up 4 bytes, that's all that means. Those 4 bytes could point to something far more useful, such as a memory area holding more than 4 characters.

You can do things like:

string s = "12345";
cout << "length of String " << s.length();
like image 45
Graham Perks Avatar answered Nov 29 '22 10:11

Graham Perks