In: Computer Science
What are differences between structure and union by coding example in C language?
1)
The struct keyword is used to define a structure
The union keyword is used to define a union
2)
When a variable is associated with a structure, the compiler
allocates
the memory for each member. The size of structure is greater than
or equal to the sum of size of its members.
When a variable is associated with a union the compiler
allocates the memoryby cinsidering the size of
the largest memory. So, size of the union is equal to the size of
largest member.
3)
In structure each member within a strucure is assigned unique
storeage area of location.
Where in union memory allocated is shared by individual memebers of
union.
4)
In structure altering value of a member will not affect other
members of the structure.
In union altering value of any of the member will alter other
memebers value;
5)
In structure individual memeber van be accessed at a time
In union only on member can be accessed at time
6)
Several members of a structure can intialize at once.
Only the first member of a union can be initialized.
// declaring structure
struct person
{
int id;
float salary;
char name[20];
};
// declaraing union
union employee
{
int empId
float rate;
char name[20];
};
If you have any query regarding the answer please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.