#include <algorithm> #include <map> #include <string> #include <iostream> using namespace std; union U1 { char c; int i; double d; } ; union U2 { char c; int i; // double d; } ; union U3 { char c; int i; // double d; } ; struct S1 { char c; int i; double d; } ; struct S2 { char c; int i; // double d; } ; struct S3 { char c; // int i; // double d; } ; int main() { cout << " U1's size = " << sizeof (U1) << endl; cout << " U2's size = " << sizeof (U2) << endl; cout << " U3's size = " << sizeof (U3) << endl; cout << endl; cout << " -------------------------------- " << endl; cout << " S1's size = " << sizeof (S1) << endl; cout << " 其中 " << sizeof ( char ) << " + " << sizeof ( int ) << " + " << sizeof ( double ) << " = " << sizeof ( char ) + sizeof ( int ) + sizeof ( double ) << endl; cout << " ---------- " << endl; cout << " S2's size = " << sizeof (S2) << endl; cout << " 其中 " << sizeof ( char ) << " + " << sizeof ( int ) << " = " << sizeof ( char ) + sizeof ( int ) << endl; cout << " ---------- " << endl; cout << " S3's size = " << sizeof (S3) << endl; cout << " 其中 " << sizeof ( char ) <<" = " << sizeof ( char ) << endl; cout << " -------------------------------- " << endl; S1 s; s.c = ' A ' ; cout << " 1 s.c = " << s.c << endl; s.d = 23.2132 ; cout << " 1 s.d = " << s.d << endl; cout << " 2 s.c = " << s.c << endl; cout << " 2 s.d = " << s.d << endl; cout << " ----------------------- " << endl; U1 u; u.c = ' A ' ; cout << " 1 u.c = " << u.c << endl; u.i = 23322 ; cout << " 1 u.i = " << u.i << endl; u.d = 23.2132 ; cout << " 1 u.d = " << u.d << endl; cout << " 2 u.c = " << u.c << endl; cout << " 2 u.i = " << u.i << endl; return 0 ; }
结果:
U1's size = 8
U2's size = 4
U3's size = 4
--------------------------------
S1's size = 16
其中 1 + 4 + 8 = 13
----------
S2's size = 8
其中 1 + 4 = 5
----------
S3's size = 1
其中 1 = 1
--------------------------------
1 s.c =
1 s.d = 23.2132
2 s.c =
2 s.d = 23.2132
-----------------------
1 u.c = A
1 u.i = 23322
1 u.d = 23.2132
2 u.c =
2 u.i = 1181975000
解释:
struct 类型的内存分配是结合内部的所有变量大小和相关的,但不是简单的相加,从上面的例子就可以看出来, struct 类型的分配的内存大小是应该内部最大数据类型的整数倍,不足一倍的部分会自动补全成一倍大小,应该是编译器为了数据整齐,处理速度会快些把。 union 类型的内存分配,只是和联合体内的最大的一个数据类型的大小相关,而且 union 内的所有数据都在一个单独的内存空间里面。这些就是上面程序出现这样的结果的原因。
所以, u.c 的值是 A ,当给联合体内的其他变量赋值之后, u.c 的值就是一个无用的信息。同样, u.i 的值最初是 23322 ,当给 u.d 赋值 23.2132 之后, u.i 的值就变得无用了。