Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c++ - Why is sizeof array(type string) 24 bytes with a single space element?

I came across a problem where I needed to find the sizeof an array to determine the length of an array. My understanding is that a char is 1 byte, a string is 2 bytes (an extra byte for the '' character).

However, I discovered that a single element of a string array is 24 bytes.

I outputted the size of a string, char, and int variables to verify my understanding. I did the same for a single element of an int, char and string arrays.

#include <iostream>

using namespace std;


int main()
{
    string strArr[1] = {" "};
    
    cout
        << sizeof " " << endl
        << sizeof strArr[0] << endl
        << sizeof strArr << endl << endl;
    
    char charArr[1] = {'a'};
    
    cout
    << sizeof 'a' << endl
    << sizeof charArr[0] << endl
    << sizeof charArr << endl << endl;
    
    int intArr[1] = {1};
    
    cout
        << sizeof 1 << endl
        << sizeof intArr[0] << endl
        << sizeof intArr << endl;
    
    return 0;
}

Expected results:

2
2
2

1
1
1

4
4
4

Actual results:

2
24
24

1
1
1

4
4
4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why is sizeof array(type string) 24 bytes with a single space element?

Because the size of a std::string object is 24 bytes (on your system).

My understanding is that a char is 1 byte

Correct.

a string is 2 bytes (an extra byte for the character).

An array of 2 char objects is indeed 2 bytes.

However, I discovered that a single element of a string array is 24 bytes.

You seem to be conflating different meanings of the word "string". While a string is indeed an array of characters, std::string is not just an array of characters. Rather, std::string is a class that represents a string.

More specifically, std::string is a class that manages a dynamically allocated array of characters. As such, the size of a string must be at least the size of a pointer that points to the allocated memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...