union
时间: 2023-06-29 09:14:08 浏览: 35
`union` 是一种特殊的数据类型,在同一内存位置存储不同的数据类型。与 `struct` 类似,但 `union` 中的所有成员共享相同的内存位置。这意味着,当您更改一个成员时,它可能会影响其他成员的值。`union` 的大小等于其最大成员的大小。
下面是一个简单的 `union` 示例:
```c
#include <stdio.h>
union data {
int i;
float f;
char str[20];
};
int main() {
union data d;
printf("Memory size occupied by data : %d\n", sizeof(d));
d.i = 10;
printf("d.i : %d\n", d.i);
d.f = 220.5;
printf("d.f : %f\n", d.f);
strcpy(d.str, "C Programming");
printf("d.str : %s\n", d.str);
return 0;
}
```
在此示例中,我们定义了一个 `union`,其中包含 `int`、`float` 和 `char` 类型的成员。我们创建了一个 `union data` 类型的变量 `d`,并打印了 `d` 的大小。我们可以看到,`union` 的大小等于其最大成员的大小,即 `float` 类型所占用的大小。我们随后设置了 `d.i`,`d.f` 和 `d.str` 的值,并打印出来。由于 `union` 中的所有成员共享同一内存位置,我们可以看到 `d.i` 和 `d.f` 的值已被覆盖。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)