by Dinesh Thakur Category: Array Pointer and Union

Both the structures and unions are syntactically and functionally same, however, they differ in the way memory is allocated to their members. While declaring structure variables, the different members are stored in different, although, adjacent memory locations whereas different members of a union variable share the same memory location. The amount of memory sufficient to hold the largest member of a union is allocated to a union variable. Thus, a union enables the same block of memory to store variable of one type at one time and of different type at another time. To understand the concept of memory allocation to a union, consider these statements.


union stu //union definition


int roll_no;       //occupies 2 bytes

char grade;      / / occupies 1 byte

}stu1;              / /union variable declaration


In these statements, a union stu is defined, which enables members of type int and char to share same space in the memory. However, if roll_no and grade belong to a structure, then they are stored in separate memory locations. For example, in this case, the compiler allocates 2 bytes to stu1, while in a structure 3 bytes will be allocated. The memory allocation of union members is shown in Figure

                              memory representation of Structure

As shown in Figure, same memory location is used for roll_no and grade members of union variable stu1. This means the same memory 1ocation can represent different values at different points of time. Hence, unions help in conserving memory space and are useful in applications where values need not be assigned to all the members at one time.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles