Reputation: 310
I have to write a piece of code and deploy it in a system with limited memory space and was thinking about char arrays vs string . I wrote the following piece of code to get a better idea.
string str="abcde";
char carray[6]={'a','b','c','d','e','\0'};
cout <<"size of char array:"<< sizeof(carray) << endl ;
cout <<"size of string:"<< sizeof(str) << endl ;
The output I get is
size of char array:6
size of string:28
So, I have 2 questions
Upvotes: 1
Views: 3691
Reputation: 11220
std::string
is a class
object in C++. The size of it is implementation-defined, but will generally require space for at least both a pointer to a heap-allocated string, and a size. The sizeof(std::string)
you are seeing may be specific to your implementation -- but it could be partially due to a small-buffer optimization where small strings are stored directly in the string.
An array of char
s is just an array of characters, so sizeof(arr)
will always be the the number of characters.
As for whether you can use std::string
: it depends on how constrained you are. std::string
will often use heap memory for larger strings, which may be hard to justify on extremely constrained systems. However, most std::string
implementations also have support for small-buffer-optimized strings, where these strings are stored directly in the std::string
rather than indirectly via heap memory
If heap memory is not justifyable, std::string
will not be a good solution for you.
However, if that's the case, I would recommend you look into either adopting an existing static_string
implementation that encodes the size as a template argument, or at least writing your own. This would be better than using char
arrays everywhere, since this becomes hard to manage long-term.
Upvotes: 3