0
string a= "Stack Overflow";
char b[]= "Stack Overflow";
cout<<sizeof(a)<<","<<sizeof(b)<<endl;

Output of above code is 4,15
Since 'a' points to the string, it has size 4 that of a string on my machine.

'b' is also pointer to string, but why it has size of 15 (i.e. of sizeof("Stack Overflow")) ?

IR-x86
  • 26
  • 4
  • A simple `std::string` can be implemented containing a pointer to a dynamically buffer containing the characters in the string and a bit of bookkeeping for the length and whatnot, but there are many ways to implement a `std::string` This one happens to pack everything it needs into 4 bytes. – user4581301 Dec 14 '17 at 18:22
  • Related [Why is sizeof(std::string) only eight bytes?](https://stackoverflow.com/questions/34560502/why-is-sizeofstdstring-only-eight-bytes) – Arun A S Dec 14 '17 at 18:24
  • @ArunAS Not really - that's a question about how `string` happens to be implemented, this one is more fundamental. – Barry Dec 14 '17 at 18:25
  • @Barry I know, that's why I posted this so OP can know how it is implemented. That itself should help understanding this more – Arun A S Dec 14 '17 at 18:27
  • `a` is **not** a pointer; its the name of a `std::string` object. And in `sizeof(b)`, `b` is **not** a pointer; it's the name of an array. In most contexts, the name of an array decays into a pointer to it first element. That does not happen when the name is the argument to `sizeof`. – Pete Becker Dec 14 '17 at 18:45
  • 1
    Actually, `std::string` typically has a size of 16 or so. It seems `string` is an alias for `char const*` in this case. – Dietmar Kühl Dec 14 '17 at 18:48
  • @Shivam How is "string" defined? What headers are you including? Can you show more of the code? – Ates Goral Dec 14 '17 at 18:58
  • @AtesGoral I have included header only. And as usual – IR-x86 Dec 15 '17 at 15:38

1 Answers1

6

Since 'a' points to the string, it has size 4 that of a string on my machine.

Not exactly.

a IS A string. It is not a pointer and, hence, does not point to a string. The implementation of string on your setup is such that sizeof(string) is 4.

'b' is also pointer to string, but why it has size of 15 (i.e. of sizeof("Stack Overflow")) ?

Not true.

b is not a pointer to a string. It is an array of char. The line

char b[]= "Stack Overflow";

is equivalent to:

char b[15]= "Stack Overflow";

The compiler deduces the size of the array and creates an array of the right size.

R Sahu
  • 204,454
  • 14
  • 159
  • 270