Size of string

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... :)
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.
Yeh that is my question.
Why String object takes 32 bytes?
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.
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.
Yeh I got it. Thanks all.
Mark as Solved please bro..
Topic archived. No new replies allowed.