Explain the result of sizeof operator for a union containing structures

不打扰是莪最后的温柔 提交于 2019-12-11 16:26:27

问题


#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;
}

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.


回答1:


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.

Why do you find it strange? Why do you call 8 "wrong value"?




回答2:


struct mystruct
{
    char cc;   //1 -byte 
    //3 bytes Added here for Padding
    float abc; //size of float is 4-bytes
};

so 1 + 3 + 4 = 8 bytes.

We knew the memory will be allocated for largest member of union. In our case both sizeof(double) = sizeof(struct mystruct) is 8.




回答3:


A union is used to place multiple members at the same memory location - you can't use more than one member at a time. All of them overlap, so the size of the union is the same as the size of the largest member.




回答4:


Union types are special structures which allow access to the same memory using different type descriptions. one could, for example, describe a union of data types which would allow reading the same data as an integer, a float or a user declared type

union 
{
    int i;
    float f;
    struct 
    {
     unsigned int u;
     double d;
    } s;
} u;

In the above example the total size of u is the size of u.s (which is the sum of the sizes of u.s.u and u.s.d), since s is larger than both i and f. When assigning something to u.i, some parts of u.f may be preserved if u.i is smaller than u.f.



来源:https://stackoverflow.com/questions/11642859/explain-the-result-of-sizeof-operator-for-a-union-containing-structures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!