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")) ?

8
  • 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. Commented Dec 14, 2017 at 18:22
  • Related Why is sizeof(std::string) only eight bytes? Commented Dec 14, 2017 at 18:24
  • @ArunAS Not really - that's a question about how string happens to be implemented, this one is more fundamental. Commented Dec 14, 2017 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 Commented Dec 14, 2017 at 18:27
  • 1
    Actually, std::string typically has a size of 16 or so. It seems string is an alias for char const* in this case. Commented Dec 14, 2017 at 18:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Then how does a store large strings in only 4 bytes?
@Shivam, it contains a pointer that points to dynamically allocated data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.