struct大小
对齐。
1 #include <iostream> 2 using namespace std; 3 4 struct S1 { 5 int a; 6 char b; 7 char c; 8 }; 9 10 struct S2 { 11 int a; 12 char b; 13 char c; 14 double d; 15 }; 16 17 struct S3 { 18 int a; 19 char b; 20 int c; 21 double d; 22 }; 23 24 struct S4 { 25 int a; 26 char b; 27 int c; 28 double d; 29 char e[9]; 30 static char f[1000]; 31 }; 32 int main(int argc, char** argv) { 33 cout << "sizeof(S1): " << sizeof(S1) << endl; 34 cout << "sizeof(S2): " << sizeof(S2) << endl; 35 cout << "sizeof(S3): " << sizeof(S3) << endl; 36 cout << "sizeof(S4): " << sizeof(S4) << endl; 37 return 0; 38 }
输出:
1 root@xxj-VirtualBox:~/interview# ./struct 2 sizeof(S1): 8 3 sizeof(S2): 16 4 sizeof(S3): 24 5 sizeof(S4): 40
static变量是不占空间的。