Structure and unions in C programming
Definitions:
Structures and unions are two of many user defined data types in C.
Both are similar to each other but there are quite some significant
differences. In this article, we will discuss about both of these data
types and differentiate both these data types based on the
functionalities.
STRUCTURES:
A structure simply can be defined as a user-defined data type which
groups logically related items under one single unit. We can use all
the different data items by accessing that single unit.
All the data item are stored in contiguous memory locations. It is not
only permitted to one single data type items. It can store items of
different data items. It has to be defined before using (Just like we
define a variable before using it in the program).
Structure definition syntax:
Struct_structure_name
Data_type_variable_name;
Data_type_variable_name;
……..
Data_type_variable_name;
};
1. #include<stdio.h>
2. struct student1
3. {
4. int rollno;
5. char name[10];
6. int marks;
7. };
8. void main()
9. {
10. int size;
11. struct student1 s={E23ITR095,"RAVIKUMAR",568};
12. printf("Roll no : %d\n", s.roll);
13. printf("Name : %s\n", s.name);
14. printf("Marks : %d\n", s.marks);
15. }
Output:
UNION:
Just like a structure, a union is also a user-defined data type that
groups together logically related variables into a single unit.
Almost all the properties and syntaxes are same, except some of the
factors.
Syntax:
Union union_name
{
Data_type variable_name;
Data_type variable_name;
……..
Data_type variable_name;
};
C Program to demonstrate how to use union
#include <stdio.h >
Union un {
Int member1;
Char member2;
Float member3;
};
Int main()
Union un var1;
Var1.member1 = 15;
Printf(“The value stored in member1 = %d”, Var1.member1);
return 0;
Output
The value stored in member1 = 15
Program to find the size
#include <stdio.h>
Union test1 {
Int x;
Int y;
} Test1
Union test2 {
Int x;
Char y;
} Test2;
Union test3 {
Int arr[10];
Char y;
} Test3;
Int main()
Int size1 = sizeof(Test1);
Int size2 = sizeof(Test2);
Int size3 = sizeof(Test3);
Printf(“Sizeof test1: %d\n”, size1);
Printf(“Sizeof test2: %d\n”, size2);
Printf(“Sizeof test3: %d”, size3);
return 0;
Output:
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40
Difference between structures and union in c
programming
Example
#include <stdio.h>
Union unionJob
{
Char name[32];
Float salary;
Int workerNo;
} uJob;
Struct structJob
Char name[32];
Float salary;
Int workerNo;
} sJob;
Int main()
Printf(“size of union = %d bytes”, sizeof(uJob));
Printf(“\nsize of structure = %d bytes”, sizeof(sJob));
return 0;
Output:
Size of union = 32
Size of structure = 40