Published: 22 Feb 2025
Reading Time: 4 min read
In C programming, both structures and unions serve the purpose of combining different data types, but they manage memory usage in distinct ways. A structure allocates separate memory for each of its members, allowing multiple members to hold values simultaneously. Conversely, a union allocates a single memory space for all its members, meaning that only one member can have a value at any given time. As a result, while structures are more versatile, unions offer greater memory efficiency. This highlights the key difference between structure and union in C.
The "struct" keyword is used to declare a user-defined data type. It creates a single datatype with a single name by combining many datatypes. Contiguous memory regions hold all of a structure's components. The sum of a structure's element sizes determines its overall memory size. The dot (.) operator can be used to access the structure elements.
struct name {
member1 definition;
member2 definition;
...
memberN definition;
};
This C program demonstrates the use of structures. It defines a Person structure with two members: name (a string) and age (an integer). The program creates a Person variable, initialises it with sample data, and prints the details (name and age) to the screen using printf.
#include <stdio.h>
// Define a structure for a 'Person'
struct Person {
char name[50];
int age;
};
int main() {
// Declare and initialize a 'Person' structure
struct Person person1 = {"John Doe", 30};
// Print the values of the structure members
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
return 0;
}
Step 1: The program includes the stdio.h library to use input/output functions like printf.
Step 2: A structure Person is defined with two members: name (a string of characters) and age (an integer).
Step 3: In the main function, a variable person1 of type struct Person is declared and initialised with the name "John Doe" and age 30.
Step 4: The program prints the values of person1's name and age using printf.
Step 5: The program finishes and exits after printing the details of person1.
Name: John Doe
Age: 30
=== Code Execution Successful ===
The "union" keyword designates a user-defined data type called a Union. It consists of a group of various data types, and every component is kept in the same memory location. In a union, a value can only be held by one member at a time. The largest union member determines the memory size.
union UnionName {
dataType member1;
dataType member2;
// more members
};
The use of a union in C, which enables the storage of various data types in the same memory address, is demonstrated by this code. An integer, a float, and a character are all present in the union value. The software assigns values to each component one by one, demonstrating how each assignment replaces the one before it. Additionally, it prints the union's size, corresponding to its biggest member's size.
#include <stdio.h>
union Value {
int i;
float f;
char c;
};
int main() {
// Create a union variable
union Value val;
// Store an integer in the union
val.i = 10;
printf("Integer: %d\n", val.i);
// Store a float in the union (this will overwrite the integer value)
val.f = 5.75;
printf("Float: %.2f\n", val.f);
// Store a character in the union (this will overwrite the float value)
val.c = 'Z';
printf("Character: %c\n", val.c);
// Print the size of the union
printf("Size of union: %zu bytes\n", sizeof(val));
return 0;
}
Integer: 10
Float: 5.75
Character: Z
Size of union: 4 bytes
=== Code Execution Successful ===
In C programming, both structures and unions are user-defined data types that allow you to group different types of variables together. However, they differ significantly in how they allocate memory and how their members are accessed. Here's a comparison of the two:
| Aspect | Structure | Union |
|---|---|---|
| Memory Allocation | In a structure, each member is allocated its own memory space. The total size of a structure is the sum of the sizes of its members (considering padding for alignment). Each member in the structure can hold different values at the same time. | In a union, all members share the same memory location. This means that only one member can hold a value at any given time. The size of its largest member determines the size of the union, as all members use the same memory space. |
| Accessing Members | You can access and store values in all members of a structure independently, as each member has its own allocated space in memory. | Since all members of a union share the same memory, storing a value in one member overwrites the values of the other members. You can only access the last assigned value, as other members may be overwritten. |
| Use Case | You use structures when you need to store several connected values of various types that can be accessed and changed separately. For instance, a structure would work best when a person's name, age, and height are displayed. | When you need to store multiple data types in the same memory area but only utilize one data type at a time, you use unions. When representing a variable that can store an integer, a floating-point number, or a character—but never more than one at once—this is helpful in scenarios when memory conservation is crucial. |
| Size | The size of a structure is the sum of the sizes of its members, possibly including padding bytes for alignment. | The size of a union is the size of its largest member. Since all members share the same memory, the union uses the amount of memory required to store the largest member. |
| Size of the Data Type | The size of a structure is the total memory required to store all its members, including padding. | The size of a union is the memory required for the largest member since they all share the same memory space. |
Here's a quick comparison using simple examples.
In this example, we'll see how a structure in C allows you to store different types of data, with each member having its own memory space. It shows that each member can hold its value independently.
#include <stdio.h>
// Structure Definition
struct student {
int id;
float marks;
char grade;
};
int main() {
// Declare and initialize structure
struct student s1;
s1.id = 101;
s1.marks = 88.5;
s1.grade = 'A';
// Display structure values
printf("Structure: \n");
printf("Student ID: %d\n", s1.id);
printf("Marks: %.2f\n", s1.marks);
printf("Grade: %c\n", s1.grade);
return 0;
}
In this example, the student structure contains three members: id (an integer), marks (a floating-point number), and grade (a character). Each of these members has its own memory space, so they store their values independently.
When you assign values to each member (s1.id, s1.marks, and s1.grade), each value remains unchanged by the other. The printf statements print all values independently, showing how they retain their individual values.
Structure:
Student ID: 101
Marks: 88.50
Grade: A
=== Code Execution Successful ===
In this one, we'll see how a union shares the same memory location for all its members. Only one member can store a value at a time, and the last assigned value is the one you can access.
#include <stdio.h>
// Union Definition
union data {
int id;
float marks;
char grade;
};
int main() {
// Declare and initialize union
union data d1;
d1.id = 101;
d1.marks = 88.5; // This will overwrite the previous value of id.
d1.grade = 'A'; // This will overwrite the previous value of marks.
// Display union values
printf("Union: \n");
printf("ID: %d\n", d1.id); // Prints overwritten value
printf("Marks: %.2f\n", d1.marks); // Prints the last assigned value
printf("Grade: %c\n", d1.grade); // Prints the last assigned value
return 0;
}
In this example, the data union contains three members: id (an integer), marks (a floating-point number), and grade (a character). All members share the same memory space, so when a new value is assigned to one member, it overwrites the previous value.
The union is initialized by assigning values to each member. The value of id is overwritten by marks, and the value of marks is overwritten by grade. When you print each member, you only see the last assigned value ('A' for grade), as the previous values have been overwritten.
Union:
ID: 1118896193
Marks: 88.50
Grade: A
=== Code Execution Successful ===
In C programming, a structure is a user-defined data type that allows you to combine multiple variable types into one cohesive entity. Each element of a structure, which may have a different data type, can be accessed with the dot operator. In situations when you need to store and handle several connected data items, structures are frequently utilised. Like every programming feature, they offer a potent means of organising data, but they also have drawbacks.
Multiple data elements of various types can be grouped together under a single name, thanks to structures. This aids in the logical arrangement of data. For instance, a structure can be used to collectively store a student's name, age, and grade in a single unit.
By providing meaningful names to data collections, the use of structures improves the readability of code. You can send a single structure variable to functions rather than several unrelated variables, which makes function calls more logical.
Data can be encapsulated thanks to structures. This makes it simpler to handle and comprehend since similar info is gathered into a single unit. Encapsulation enhances code organisation and is a basic idea in many programming paradigms.
When working with linked data types, structures enable the effective use of memory. A structure stores all related data in a single memory block that may be altered as a single entity instead of employing distinct variables for every piece of data.
Structures are quite flexible and can be readily expanded by adding new members without changing the current code. You can add new properties to the structure without changing a lot of the existing code if the requirements change.
You can store many instances of a comparable type of data by using arrays created with structures. Working with huge data sets that have similar characteristics, such as a list of employees or students, is helpful.
Because of alignment constraints, memory padding frequently occurs in C structures. This implies that even though the structure's overall size may appear smaller, padding bytes provided for alignment purposes may cause it to appear larger in memory. Memory consumption may become inefficient as a result.
A structure's size is set once it has been defined. This implies that you could have to construct a structure with the maximum sizes if you need to store data of different sizes, resulting in memory waste.
Managing and modifying the data can get complicated when working with large structures, particularly those with several or nested members. It may make the code more complex to maintain and debug.
More intricate syntax is needed for structures in order to access their members (for example, by using the dot operator). This can make the code more prone to errors and more difficult to read, particularly when passing code between methods or working with nested structures.
C structures lack built-in methods or functions to manipulate the data they store, in contrast to objects in object-oriented programming (OOP). You must write functions independently to process or modify the data inside structures.
C structures lack sophisticated capabilities like inheritance and polymorphism, which are necessary for more intricate data modelling because they are not object-oriented. They are, therefore, less adaptable for use when object-oriented design concepts are necessary.
C structures offer a productive method for managing and organising various linked data. They provide notable benefits regarding data encapsulation, readability, and memory efficiency. They do have several disadvantages, though, like memory padding, the intricacy of huge structures, and the absence of sophisticated capabilities present in object-oriented programming. One must know the benefits and drawbacks of using structures in C programming efficiently.
A union in C is a user-defined data type that permits storing several types of data in the same memory address. When only one member needs to be used at a time, it is helpful for memory-efficient storage.
Because they keep all of their members in one memory place, unions are memory-efficient. When only one member is required at a time, the union's size is determined by the size of its largest member, which helps conserve memory.
A union enables you to store multiple types of data, but only one at a time, without using additional memory. This is very helpful for applications with little memory, such as embedded devices.
Unions make it easier to manage various kinds of data. Data handling and memory management are made simpler by using a single union variable to hold many data kinds rather than having distinct variables for each type.
When you wish to interpret the same data in several ways, unions might be helpful. For instance, depending on the circumstance, the same data could be handled as a character, float, or integer, providing flexibility in data representation.
Unions can be used to map data structures that represent various data types or permit access to the same memory address in various formats in low-level programming, such as in hardware programming or operating system architecture.
A value stored in one member of a union overwrites the values of all other members since all members share the same memory space. If not handled appropriately, this could result in data loss.
A union is only able to hold one value at a time. In contrast to structures where each member has its own memory space, unions are inappropriate if you need to store numerous values simultaneously.
It can be difficult to track the type of data currently stored because you can only access one union member at a time. Debugging and code maintenance may become more challenging as a result.
Type safety is not included in unions; hence, no automated verification guarantees that the right type is accessed. If the incorrect member is accessed, this could result in undefinable behaviour.
Unions can make programs more difficult even when they save memory. To prevent problems like data corruption, developers must make sure that the data is managed properly and know when to access each member.
When it comes to memory efficiency and adaptability for managing various kinds of data, unions in C provide substantial benefits. They do have drawbacks, though, such as the possibility of data management complexity, restricted concurrent access to members, and overwriting of data. When choosing to include unions in a program, it's critical to comprehend these trade-offs.
Structures and unions in C are versatile tools that help organize data efficiently. Knowing when to use each is crucial for writing optimal and maintainable code.
Structures are ideal when you need to group different data types that are related but should be stored independently. For example, if you want to represent a student's information, such as their id, name, and marks, a structure is the best choice. This is because each member can hold its own value without affecting the others. Structures are widely used in scenarios like:
Unions are useful when you need to store different data types in the same memory space, but only one value is needed at any given time. This makes them memory efficient but also limits access to only one member at a time. Unions are commonly used in:
Structures and unions in C share several similarities despite their differences in memory management. Understanding these common features helps in using them effectively:
C provides a variety of data types to handle different kinds of data efficiently. These are categorized as follows:
1. Primary Data Types: int, float, double, char, and void.
2. Derived Data Types: Arrays, pointers, and functions.
3. User-Defined Data Types: Structures (struct), unions (union), enumerations (enum), and typedef.
4. Complex Data Types: Pointers to functions, pointers to arrays, and structures with pointers.
In summary, unions and structures aggregate different data, but they allocate memory differently. A union allots the same memory space to all of its members, but a structure allots distinct memory to each member. While unions are memory-efficient when only one value needs to be saved at a time, structures are appropriate for holding numerous independent values.
While a union uses the same memory space for all of its members, a structure allots distinct memory for each member.
Yes, several members of various data kinds can be stored independently within a structure.
No, a union can only store and access one member at a time because all members share the same memory location.
A structure utilises memory for each member separately, whereas a union uses only the memory needed for its largest member, making it more memory-efficient.
Use a structure when you need to store several values at once, each with its own memory space. Use a union when storing multiple kinds of data, but only one at a time.
Complete Guide on String Functions in C - Learn essential string functions in C with syntax, examples, memory rules, and safe practices. (29 Dec 2025, 5 min read)
Mastering Insertion Sort in C: Code, Logic, and Applications - Understand insertion sort in C with easy-to-follow logic, code examples, and practical tips. (29 Dec 2025, 6 min read)
Quick Sort Algorithm Explained: Steps, Code Examples and Use Cases - Learn the Quick Sort Algorithm with clear steps, partition logic, Python & C++ code examples. (28 Dec 2025, 6 min read)
Switch Statement in C: Syntax, Flowchart & Sample Programs - Learn how to use the switch statement in C programming with simple syntax and real-life examples. (27 Dec 2025, 6 min read)
The Ultimate Guide to Binary Search Algorithm in C - Learn the Binary Search Algorithm with steps, examples, and efficiency insights. (27 Dec 2025, 8 min read)
Merge Sort in C: A Step-by-Step Guide with Code Examples - Learn how Merge Sort works in C with easy-to-follow examples and step-by-step logic. (26 Dec 2025, 8 min read)
About NxtWave: This content is provided by NxtWave, an educational platform offering comprehensive programming courses and resources.
Contact Information:
Course Offerings: