0
#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.

4

4 回答 4

6

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"?

于 2012-07-25T04:45:04.967 回答
2
struct mystruct
{
    char cc;   //1 -byte 
    //3 bytes Added here for Padding
    float abc; //size of float is 4-bytes
};

所以 1 + 3 + 4 = 8 个字节。

我们知道内存将分配给最大的联合成员。在我们的例子中,sizeof(double) = sizeof(struct mystruct) 都是 8。

于 2012-07-25T04:59:56.457 回答
1

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.

于 2012-07-25T04:45:36.870 回答
0

联合类型是允许使用不同类型描述访问相同内存的特殊结构。例如,可以描述一个数据类型的联合,它允许读取与整数、浮点数或用户声明的类型相同的数据

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

在上面的示例中,u 的总大小是 us 的大小(即 usu 和 usd 的大小之和),因为 s 大于 i 和 f。给ui赋值时,如果ui小于uf,uf的某些部分可能会被保留

于 2012-07-25T04:57:23.460 回答