gpt4 book ai didi

c - C 中 union 体的大小

转载 作者:行者123 更新时间:2023-11-30 21:13:27 27 4
gpt4 key购买 nike

union 的大小等于其中最大成员的大小。但在下面的 union 中,大小显示为 8 字节。 int 和 float 的大小为 4 字节。为什么显示8字节?

union data {
int i;
float f;
char *str;
};

最佳答案

#include <stdio.h>

union data_t {
int i;
float f;
char *str;
};

int main()
{
union data_t data;
printf("%zu\n%zu\n%zu\n", sizeof (data.i), sizeof (data.f), sizeof (data.str));
printf("\nsizeof(char*): %zu\nsizeof(char): %zu\n", sizeof(char *), sizeof(char));
}

输出:

$ ./a.out 
4
4
8

sizeof(char*): 8
sizeof(char): 1

关于c - C 中 union 体的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016607/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com