What is the size of string
here when i store a very longer string b is able to store complete string
but when i cout its size it shows it size 8 bytes whats wrong here>?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
char c;
string b;
cout<<"enter any string"<<endl;
getline(cin,b);
cout<<b<<endl;
cout<<sizeof(b)<<endl;
return 0;
}
std::string is a struct (class) that contains the pointer to an allocated memory where it stores your entered string. So the class contains only the pointer not the allocated character array. This pointer (with some other data members of class std::string) is taking into account when you apply sizeof operator. The size of the class does not depend of the number of characters for which the class allocates in the heap a storage.
There is an object of class std:;string that can be allocated for example in the stack and there is a character array that this object allocates in the heap that to store a string. sizeof( std:;string ) gives you the size of the object not of the allocated by the object memory in the heap.