Nostalgic
Nostalgic

Reputation: 310

Size of string vs size of char array in c++

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

  1. Can I conclude that using the string will be a foolish idea given that it is taking much more space, given that memory space is tight and the max chars in my array wont be greater than 10?
  2. Why the hell is size of string showing as 28? on what basis?

Upvotes: 1

Views: 3691

Answers (1)

Bitwize
Bitwize

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 chars 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

Related Questions