1、union s1 { int a; char b; char c; }; sizeof(union s1) = ? 2、union s2 { char a; int b; char c; }; sizeof(union s2) = ?
时间: 2024-04-15 15:25:34 浏览: 26
1、union s1 的大小取决于其成员变量中占用空间最大的那个变量,即 int 和 char c。int 类型通常占用 4 个字节,而 char 类型占用 1 个字节。所以 sizeof(union s1) = 4。
2、同理,union s2 的大小取决于其成员变量中占用空间最大的那个变量,即 int 和 char c。所以 sizeof(union s2) = 4。
相关问题
struct s1 { int a; char b; char c; }; sizeof(struct s1) = ?
根据内存对齐的原则,结构体中的成员变量会被调整到内存地址是其自身大小的倍数的位置。因此,结构体 `s1` 中的 `int a` 会被调整到 4 字节对齐,而 `char b` 和 `char c` 会被调整到 1 字节对齐。因此,`s1` 的大小为 4 + 1 + 1 = 6 字节。所以,`sizeof(struct s1) = 6`。
struct s2 { char a; int b; char c; }; sizeof(struct s2) = ?
根据内存对齐的原则,结构体中的成员变量会被调整到内存地址是其自身大小的倍数的位置。因此,结构体 `s2` 中的 `char a` 和 `char c` 会被调整到 1 字节对齐,而 `int b` 会被调整到 4 字节对齐。因此,`s2` 的大小为 1 + 4 + 1 = 6 字节。所以,`sizeof(struct s2) = 6`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)