Structure:
In
C programming, structures (often referred to as "structs") are
user-defined data types that allow you to group together different variables
under a single name. A structure can hold various types of data such as
integers, floats, arrays, and even other structures, enabling you to create
more complex data structures.
This code uses a structure
Here
m is the structure variable used to access elements of the structure
The
same program can be written using a union to get the same result.
The
difference between structures and unions is:
Though
unions are similar to structure in so many ways, the difference between them is
crucial
to understand. This can be demonstrated by this example:
#include
<stdio.h>
union
job
{
char
name[32];
float
salary;
int
worker_no;
}u;
struct
job1
{
char
name[32];
float
salary;
int
worker_no;
}s;
int
main()
{
printf("size
of union = %d",sizeof(u));
printf("\nsize
of structure = %d", sizeof(s));
return
0;
}
Output:
size
of union = 32 size of structure = 40
There is difference in memory allocation between union and structure as suggested in above example. The amount of memory required to store a structure variable is the sum of memory size of all members.
But, the memory required to store a union variable is the memory required for largest element of an union.
Also,
all members of structure can be accessed at any time. But, only one member of
union can be accessed at a time. In case of union other members will contain
garbage value.
0 Comments