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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…