Difference between Structures and Unions

johnson10001's Avatar, Join Date: Aug 2014
Newbie Member
Hi every one..I am new to programming..Can any one tell me the difference between structures and unions in C
1
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
There are quite a few difference between struct and union.
  • Structure has memory equal to sum of all member variables where as union has memory equal to hold the largest variable type of all the member variables.
  • In Structure all members variables can be used to store data and retrieve it where as in union only one member variable can be used.
You can read more about unions here along with examples.
0
bigdatatraining's Avatar, Join Date: Dec 2015
Newbie Member
Hi..To know more details about the difference between structure and union, please refer this link.
Structure
Union
1.The keyword struct is used to define a structure
1. The keyword union 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 sizes of its members. The smaller members may end with unused slack bytes.
2. When a variable is associated with a union, the compiler allocates the memory by considering the size of the largest memory. So, size of union is equal to the size of largest member.
3. Each member within a structure is assigned unique storage area of location.
3. Memory allocated is shared by individual members of union.
4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.
4. The address is same for all the members of a union. This indicates that every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
5. Altering the value of any of the member will alter other member values.
6. Individual member can be accessed at a time
6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at once.
7. Only the first member of a union can be initialized.