解释包含结构的联合的 sizeof 运算符的结果 [英] Explain the result of sizeof operator for a union containing structures
问题描述
#include<stdio.h>
struct mystruct
{
char cc;
float abc;
};
union sample
{
int a;
float b;
char c;
double d;
struct mystruct s1;
};
int main()
{
union sample u1;
int k;
u1.s1.abc=5.5;
u1.s1.cc='a';
printf("\n%c %f\n",u1.s1.cc,u1.s1.abc);
k=sizeof(union sample);
printf("%d\n\n",k);
return 0;
}
运算符的大小返回 8
我仍然能够访问结构元素,一次多个,并且 sizeof
运算符仍然返回最大大小我假设的原始数据类型.为什么会出现这种行为?实际分配的大小是8
吗?并且 sizeof
返回错误值?还是实际分配的大小是8
?那么结构是如何容纳的呢??如果我们使用 malloc
和 sizeof
分配一个联合数组,它会在这种情况下分配足够的空间吗?请详述.
The size of operator is returning 8
I am still able to access the structure elements, more than one at a time and still the sizeof
operator is returning the max size of primitive data types i assume. Why is this behavior? Is the size actually allocated is 8
? and the sizeof
is returning a wrong value? Or is the actual allocated size is 8
? Then how is the structure accommodated?? If we allocate an array of unions using malloc
and sizeof
will it allocate enough space in such case? Please eloborate.
推荐答案
通常,联合的大小是其最大成员的大小.最大的成员 [可能] 是您的结构成员以及 double
成员.两者的大小都是 8.所以,正如 sizeof
正确告诉你的,联合的大小确实是 8.
Typically, the size of the union is the size of its biggest member. The biggest member is [likely] your struct member as well as the double
member. Both have size 8. So, as sizeof
correctly told you, the size of the union is indeed 8.
你为什么觉得奇怪?为什么称8为错误值"?
Why do you find it strange? Why do you call 8 "wrong value"?
这篇关于解释包含结构的联合的 sizeof 运算符的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!