sizeof string

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>

using namespace std;

int main()
{
   char c;
   string b;
   cout<<"enter any string"<<endl;
   getline(cin,b);
   cout<<b<<endl;
   cout<<sizeof(b)<<endl;

    return 0;
}
sizeof( b ) is equal to sizeof( std::string )

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.
Last edited on
so according to you this memory allocated in heap...?
Last edited on
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.
Last edited on
okay gotcha!
Topic archived. No new replies allowed.