Difference between Structure and Union in C

Question: What is the Difference between Structure and Union in C?

Answer: Unions and structures are declared alike but they work differently. Let’s discuss differences Structure and Union in C. Consider the declarations below,

typedef union {
               int a;
               float b;
               char c;
    } A_union;
 
typedef struct {
               int a;
               float b;
               char c;
    } B_struct;

Notice here that both ‘A_union’ and ‘B_struct’ have the same member list declaration but storage amount allocated to their variables differs. Not taking into account boundary alignment on certain systems, type ‘B_struct’ allocates 9 bytes to its variables while type ‘A_union’ allocates storage as large as largest member of it that is 4 bytes, since both ‘float’ and ‘int’ takes 4 bytes on Linux machine.

Since storage is allocated to all members in a structure, we can access either or all members at all times. On the contrary, union is allocated storage as the size of largest member of it. Only one member of it can be accessed at a time. Actually, a union is useful where its different members can access the same memory location but at different times. For example,

int main(void)
{
    A_union x;    /* 'x' is allocated 4 bytes of storage */
 
    x.a = 10;     /* accessed this storage as integer */
    printf("x.a is an integer: %d\n", x.a);
 
    x.b = 23.34;  /* accessed the same storage, this time, as 'float' */
    printf("x.b is a float: %.2f\n", x.b);
 
    x.c = 'A';    /* same storage accessed as character this time */
    printf("x.c is a character: %c\n", x.c);
 
    return 0;
}

Output of the above program as follows,

advertisement
advertisement
Memory allocated to 'x' of type A_union is: 4 bytes.
 
x.a is an integer: 10
x.b is a float: 23.34
x.c is a character: A

So, what you noticed in the output of above program, same memory location, 4 bytes allocated to ‘x’, is accessed by each of its member’s but at different times.

Let’s see if we can initialize all members of ‘x’, as we had initialized structure members several times earlier,

int main(void)
{
    /* initializing all members of 'x' */
    A_union x = {10, 23.34, 'A'};
 
    return 0;
}

Output of the program is as follows,

Note: Join free Sanfoundry classes at Telegram or Youtube
In function ‘main’:
warning: excess elements in union initializer [enabled by default]
warning: (near initialization for ‘x’) [enabled by default]
warning: excess elements in union initializer [enabled by default]
warning: (near initialization for ‘x’) [enabled by default]

Notice here that you can’t initialize all members of union ‘x’ in the same memory location, in just 4 bytes allocated to ‘x’. Does this mean if we can initialize either of the members of ‘x’? Let’s try this also,

int main(void)
{
    /* initializing only one member 'x' */
    A_union x = {23.34};    /* float value initializing the 'x' */
 
    printf("Memory allocated to \'x\' of A_union is: %d bytes.\n",
            sizeof(x));
    puts("");
 
    printf("x.a is an integer: %d\n", x.a);
    printf("x.b is a float: %.2f\n", x.b);
    return 0;
}

Let’s analyse the output below,

advertisement
Memory allocated to 'x' of A_union is: 4 bytes.
 
x.a is an integer: 23
x.b is a float: 0.00

So, what you noticed here? We tried to initialize the memory location with float value ‘23.34’. Since first member of ‘x’ is an integer, initializer ‘23.34’ implicitly type cast to an integer value ’23’, saved ’23’ into that memory location and printed this when we wished to obtain that value. When bits in the same memory location interpreted as a float value because of ‘%f’ format specifier of next printf statement, a float value ‘0.00’ printed. Actually, integer value ’23’ now in the memory location again type cast to float value and printed as ‘0.00’.

So, we here observed that only the first member of union can be initialized and same memory location can be accessed by all members of union but at different times.

advertisement

Here are the Difference Between Structure and Union in C

Structure Union
Structure Syntax:
typedef struct {
int a;
float b;
char c;
} B_struct;
Union Syntax:
typedef union {
int a;
float b;
char c;
} A_union;
A structure is a data type that groups together related data items into a single unit. Each data item in a structure is called a member, and can be of any type, including another structure. A union is very similar to a structure, except that all members share the same memory location. This means that only one member can be stored in memory at any given time.
A structure declaration always includes the keyword struct, followed by the structure’s name. A union declaration always includes the keyword union, followed by the name of the union.
Each member of the structure is stored in its own memory location. All members of the union are stored in the same shared memory location.
The size of a structure is the sum of the size of its member. The memory occupied by a union is equal to the maximum size of one of its members. Hence the size of the union would be equal to the size of its largest data member.
Structure allows a user to initialise multiple members at the same time. A user can only initiate the first member of a Union at a time.

Now, question is where do we use unions and where structures? We’ll see this later.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.