c++ sizeof( string )

后端 未结 8 1526
陌清茗
陌清茗 2020-12-09 13:59
#include 
#include 

int main(int argc, char *argv[])
{
   cout << "size of String " << sizeof( string );
               


        
相关标签:
8条回答
  • 2020-12-09 14:54

    It isn't clear from your example what 'string' is. If you have:

    #include <string>
    using namespace std;
    

    then string is std::string, and sizeof(std::string) gives you the size of the class instance and its data members, not the length of the string. To get that, use:

    string s;
    cout << s.size();
    
    0 讨论(0)
  • 2020-12-09 14:54

    No, it means that the sizeof the class string is 4.

    It does not mean that a string can be contained in 4 bytes of memory. Not at all. But you have to difference between dynamic memory, used to contain the size characters a string can be made of, and the memory occupied by the address of the first of those characters

    Try to see it like this:

    contents  --------> |h|e|l|l|o| |w|o|r|ld|\0|
    

    sizeof 4 refers to the memory occupied by contents. What it contents? Just a pointer to (the address of ) the first character in the char array.

    How many characters does a string can contain ? Ideally, a character per byte available in memory.

    How many characters does a string actually have? Well, theres a member function called size() that will tell you just that

    size_type size() const
    

    See more on the SGI page !

    0 讨论(0)
提交回复
热议问题