What are differences between Structure and Union in c?

28 Dec 2022 Balmiki Mandal 0 C Programming

Structures vs. Unions in C

Structures and unions are both user-defined data types in C. They can be used to store data of different types under a single name. However, there is a key difference between the two: structures allocate separate memory locations for each member, while unions share the same memory location for all members.

Key differences between structures and unions:

Characteristic Structure Union
Memory allocation Separate memory location for each member Shared memory location for all members
Size Size is equal to the sum of the sizes of all members Size is equal to the size of the largest member
Accessing members Each member can be accessed individually Only one member can be accessed at a time
 

Example of a structure:

struct student {
  int id;
  char name[20];
  float marks;
};

This structure defines a data type called student that can be used to store information about a student, such as their ID, name, and marks.

Example of a union:

union employee {
  int id;
  char name[20];
  float salary;
};

This union defines a data type called employee that can be used to store information about an employee, such as their ID, name, or salary. However, only one of these values can be stored at a time, since the union only has one memory location.

When to use structures and unions:

  • Structures should be used when you need to store multiple values of different types under a single name and you need to be able to access each value individually.
  • Unions should be used when you need to store multiple values of different types under a single name and you only need to be able to access one value at a time.

Top Resources


Union in c

Printing The Binary formate of float using union

Nested union in C

Assignment in union in c programming

What is a union? What are the advantages & Disadvantages in c?

What are differences between Structure and Union in c?

advantages of union in c

 bubble sort using union in c

Write a C Program to prove we are working on little Endian environment using a union

Enroll Now:

C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [[email protected]].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.