when i run the following code https://ide.codingblocks.com/s/49811 i get output as 8, 32 respectively, i woulld like to know why this is happening as both are one and the same thing i guess char a[]=“amazing” and string s=“amazing” what is the difference b/w these two
sizeof(char array) v/s sizeof(string)
Hi Aayush,
When you declare a string as char str[]=“abc”, the sizeof(str) will give 4 because there are 3 characters in the array + ‘\0’.
On the contrary, when you declare a string as string str=“abc”, std::string implementations save very small strings directly on the stack in a statically sized char array instead of using dynamic heap storage. This is known as Small (or Short) String Optimisation (SSO). On typical architectures where sizeof (void*) = 8, this gives us a total size of 32 bytes.
1 Like