Structure Vs Union In C: Definition, Syntax, Advantages/Disadvantages
We are aware of the fact that an array is a collection of items of the same type, but there are multiple occasions when we need to hold items of various types. In such cases, one can use structures and unions.
Ideally, structure and union would be a collection of different variables grouped together under a single name. Both structure and union are container data types that may hold any object, including other structures, unions, and arrays. The structure is mostly used to store complex data. Syntactically, a union is analogous to structure. Let's take a closer look at the similarities and differences between structure and union.
What is a Structure?
A structure is a collection of multiple values, which may or may not be of the same type. It is a user-defined data type. In a program, the struct keyword is used to define a structure data type. A single name or pointer can be used to refer to the entire structure.
Structures allow you to combine a number of linked variables of various types into the memory size of a single unit. "Members" are the variables in a structure. Structure members can also be accessed separately. The components of a structure are stored in contiguous memory locations.
When you declare a structure, you establish a template that can be used to construct structure objects with the same data members and member functions. Until a structure variable is formed, the members of the structure do not occupy memory. Structure data types are a handy technique to combine related data into a single variable. We use the struct statement to define a structure.
Syntax of struct
struct struct_name {
structure element 1;
structure element 2;
. . .
structure element n;
};
Example:
struct student {
char name[20];
int rno;
float fees;
};
struct student s; // declaring ‘s’ as a student struct
There is another way of declaring the structure
struct student {
char name[20]; int rno; float fees;
};s1,s2
Use the second strategy if the number of variables is fixed. It saves you time by eliminating the need to declare a variable in the main() method.
Structure data types are a convenient way to group together related data into a single variable.
struct rectangle {
int l;
int b;
};
l and b are called the members (or fields) of the rectangle struct.
Typedef is used for renaming an existing structure type.
struct rectangle {
int l;
int b;
};
typedef struct rectangle rect;
Using and defining structs
A structure variable's members can be initialized or accessed using the dot operator (.).
struct rectangle r; // declaring ‘r’ as a rectangle struct
r.l = 5;
r.b = 10;
The above is equivalent to
struct rectangle r = {5, 10};
The (.) dot operator is used to access fields.
printf(“Rectangle is (length = %d, breadth = %d)”, r.l, r.b);
We are unable to do arithmetic operations such as +, -, *, /, and other similar operations. Structure variables are also incompatible with relational and equality operators. We can, however, replicate one structure variable to another if they are both parts of the same structure.
Code :
Output:
Enter Name:
Saurav
Enter Roll No:
25
Enter fees:
125200.25
Details are:
Saurav
25
125200.250000
Array of structure
We can also create an array of structures just like we create an array of integers or an array of characters. An array of structures can also be used to store multiple data of the same data types.
Structure Within a Structure
When a structure is nested, it signifies that one or more structure variables are contained within another structure.
We can access the members of the inner structure as well as other members by using (.).
Pointer to a structure
When you have a variable that contains a struct, you can use the dot operator to access its fields (.). This will not work, though, if you have a pointer to a struct. To access its fields, you must use the arrow operator (->).
Code:
Output:
Enter Roll no, Name, Marks : 18 Saurav 95
Student Details are:
Roll No is 18
Name is Saurav
Marks is 95.000000
Self Referential Structure
Structures that have one or more pointers that point to the same type of structure as their member are known as self-referential structures.
In the above code ‘next’ is a pointer to a structure of type node. As a result, the 'node' structure is a self-referential structure with the referring pointer 'next.'
Structure as Function Argument
Both call-by-value and call-by-reference methods can pass the entire structure variable to the function.
The parameters of each argument must match those of the function parameter. When there are a significant number of structure members, passing them is inefficient. Passing a copy of the structure will be inefficient if the structure is huge.
The structure allows a single parameter to pass an entire collection of records to any function. A structure pointer could be passed to a function. The structure's address is passed as an actual argument in this situation.
Advantages of Structure
1. Because we represent complete records with a single name, it makes it very straightforward to manage the entire record.
2. The structure allows a single argument to pass an entire collection of records to any function.
3. To hold numerous data types of the same type, an array of structures can be built.
4. More than one data type of the same item is stored in a structure.
Disadvantages of Structure
1. When one data structure in a program is changed, it necessitates modifications in multiple other areas. As a result, keeping track of all the changes becomes tough.
2. The structure consumes more storage space because it allocates memory to all of the data members,
3. Because all of the data must be stored, the structure takes more time.
4. When one data structure in a program is changed, it necessitates modifications in multiple other areas. As a result, keeping track of all the changes becomes tough.
What is a Union?
A union is a collection of many values that aren't necessarily of the same type. Within the union definition, memory space is only allocated to the largest size of the variable.
Union variables share the exact memory location in case of memory allocation, unlike the structure that has a separate memory location. Union does not enable flexible arrays, If we make changes in one member then it will be reflected to other members as well. A union is a useful approach for using a single memory location for several tasks.
At any given time, only one member of the union can be accessible. A union statement is defined and created using the union keyword. The syntax of unions is very similar to that of structures.
Example:
union student {
char name[50];
int rno ;
float fees;
};
union student s;
s.rno = 20;
We can access members of union with the help of dot operator (.)
printf("rno = %d\n", s.rno); // 20
If you try to modify the value of any of the members of the union s, the other member will be adjusted to that value automatically.
s.fees = 1900;
printf("rno = %d\n", s.rno); //1900
printf("fees = %d\n", s.fees); //1900
Pointer to a union
The pointer to a union can be constructed in the same way as the structure pointer. The memory address of the union is held by the pointer. To access its fields, you must use the arrow operator (->).
union student *su;
su = &s;
printf("%f\n", su->fees); //1900
Code:
Output:
a = 78
b = N
Union as Function Parameter
The union, like the structure, may be passed to functions using both call-by-value and call-by-reference methods.
Output:
Roll No is 18
Marks of p c m is 92 89 95 respectively
Advantages of Union
1. When utilizing a union, only the biggest data member may be directly accessed.
2. When you wish to use less memory for different data members, this technique is suggested.
3. When compared to structure, it takes up less memory.
Disadvantages of Union
1. The union data members aren't all initialized, therefore they're utilized by exchanging values one at a time.
2. It only permits one data member to be accessed at a time.
3. All of the data members of a union are given the same common memory space, which is shared by all of them.
Similarities between Structure and Union
In C programming language, both structures and unions are used to define custom data types that can hold multiple pieces of data. Despite their differences, they share some similarities:
-
Custom Data Types: Both structures and unions allow you to define custom data types by grouping different variables of various data types under a single name.
-
Member Access: You can access the individual members of both structures and unions using the dot (.) operator. For example, if you have a structure or union named myData, and it contains a member called x, you can access it like myData.x.
-
Memory Allocation: Both structures and unions allocate memory for their members. The size of a structure is the sum of the sizes of its members, while the size of a union is determined by the size of its largest member.
-
Initialization: You can initialize both structures and unions at the time of declaration, just like any other variable in C.
Difference between Structure and Union
Here are some of the major distinctions between structure and union in the C programming language :
Parameter | Structure | Union |
Accessibility | We can access all the members of the structure at anytime | Only a single entity of a union can be accessible at any time. |
Memory Allocation | Memory is allocated for all variables | Allocates memory for the variable which requires more memory |
Change in value of variables | Changing a variable's value has no effect on other variables. | Changing the value of one variable member will have an impact on the other variables. |
Value type | Structure stores unique values for each member | The identical value is stored for all members. |
Value storage | At any point in the program, all variable members store some value. | At any given point in the program, exactly one data member stores a value. |
Initialization | All members of the structure can be initialized | Only the first member of a union can be initialized |
Keyword | keyword struct is used to declare structure | keyword union is used to declare union |
Size | The sum of the sizes of all the data members equals the size of the structure | The size of union is equivalent to the largest member's size. |
Syntax |
Syntax of struct
|
Syntax of union
|
|
|
|
Summing up...
To conclude, structure and union are container datatypes that hold members of various types. Unions are significantly more portable and easier to debug than structures, which are more adaptable, versatile, and capable of accessing numerous objects at the same time. You may retrieve any member at any moment in the structure. In a union, on the other hand, you can only access one member at a time.
You might also be interested in reading:
- String Array In C++ 8 Ways To Create & Access Element (+Examples)
- Difference Between Active And Passive Cyber Attacks Explained
- Compiler Vs Interpreter: What's the Difference?
- Difference Between Sensor And Transducer Explained!
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment