union共用体使用技巧
union
- 在 C 语言中,union 是一种特殊的数据类型,它允许在同一内存位置存储不同的数据类型。union 的大小由其最大的成员确定,所有成员共享同一块内存。
1typedef struct {
2 int a;
3 int b;
4} Struct1;
5typedef struct {
6 double c;
7 double d;
8} Struct2;
9union MyUnion {
10 Struct1 s1;
11 Struct2 s2;
12};
在这个例子中,Struct1 的大小是 8 字节(假设 int 的大小是 4 字节),Struct2 的大小是 16 字节(假设 double 的大小是 8 字节)。因此,MyUnion 的大小是 16 字节,即 Struct2 的大小。
注意,在任何时候,MyUnion 只能存储 s1 或 s2,不能同时存储两者。如果你先写入 s1,然后写入 s2,那么 s1 的值就会被覆盖。