Structure and Union
- Structure is one of the user-defined data type in which allows combining data of different types. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. For example if we have to store information of employees of the company, which all have employee’s name, age, department, phone number, address etc. which includes string values, integer values etc. then in these case structure will be used instead of arrays. Data in structure is stored as records.
- A union is a user defined data type which may hold members of different sizes and type. Union uses a single memory location to hold more than one variable.
- When a variable is associated with a structure, the compiler allocates the memory for each member whereas in a union the compiler allocates the memory by considering the size of the largest memory.
- The size of the structure is greater than or equal to the sum of sizes of its members whereas in union the size is equal to the size of largest member.
- Each member within a structure is assigned unique storage area of location while in union; memory allocated is shared by individual members.
- The address of each member in structure will be in ascending order. This indicates that memory for each member will start at different offset values. In union, the address is same for all the members of a union. This indicates that every member begins at the same offset value.
- Altering the value of a member will not affect other members of the structure. While on the contrary, if the value of any of the member is altered it will alter the values of other members.
- Individual member of structure can be accessed at a time while in union only one member can be accessed at a time.
- Several members of a structure can be initialized at once. On the other hand only first member of a union can be initialized.