sasidhar
sasidhar

Reputation: 7752

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

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.

Upvotes: 0

Views: 9085

Answers (4)

Jeyaram
Jeyaram

Reputation: 9494

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.

Upvotes: 2

Shiridish
Shiridish

Reputation: 4962

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.

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320671

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

Upvotes: 6

Mark Ransom
Mark Ransom

Reputation: 308452

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.

Upvotes: 1

Related Questions