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.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
sasidhar
  • 7,523
  • 15
  • 49
  • 75

4 Answers4

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

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • how does it accommodate the `structure` member within?? – sasidhar Jul 25 '12 at 04:46
  • @sasidhar: What do you mean by your "how"? The size of your struct member is probably 8 (check it). The size of the union is 8. So, the union is indeed big enough to accommodate the struct member. Where do you see the problem? – AnT stands with Russia Jul 25 '12 at 04:47
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.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

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.

Shiridish
  • 4,942
  • 5
  • 33
  • 64