Size of string

Sep 10, 2015 at 10:37am
Please have a look to below code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    char* str = "akash";
    string st = "akash";

    cout<<"Size of char* : "<<sizeof(str)<<endl;            // 4
    cout<<"Length of str : "<<strlen(str)<<endl<<endl;      // 5
    
    cout<<"Size of string : "<<sizeof(st)<<endl;            // 32
    cout<<"Length of string : "<<st.length()<<endl;         // 5
    

OutPut:

Size of char* : 4
Length of str : 5

Size of string : 32
Length of string : 5



Why the size of string object is 32?

Please reply... :)
Sep 10, 2015 at 10:54am
The sizeof() on line 7 tells you that the complex string structure requires 32 bytes. It has nothing to do with the data (the c string) of that string.
Sep 15, 2015 at 5:52am
Yeh that is my question.
Why String object takes 32 bytes?
Sep 15, 2015 at 7:13am
It depends on how the string class is implemented. When I compile your code with GCC it says sizeof(st) is 8. If you really want to know you'll have to look inside the code for std::string that your compiler is using.
Sep 15, 2015 at 7:42am
It depends on the implementation of string. If you want to find out why exactly 32 bytes you need to find out what member variables that class harbors.
Sep 15, 2015 at 9:15am
Yeh I got it. Thanks all.
Sep 15, 2015 at 3:40pm
Mark as Solved please bro..
Topic archived. No new replies allowed.