Structures and unions help group different data types together. They let you store related information in one place.
Structure vs union comparison
struct StructureName {
dataType1 member1;
dataType2 member2;
...
};
union UnionName {
dataType1 member1;
dataType2 member2;
...
};A structure stores all members separately, each with its own memory.
A union shares the same memory space for all members, so only one member can hold a value at a time.
struct Person {
char name[20];
int age;
float height;
};union Data {
int i;
float f;
char str[20];
};This program shows how a structure keeps all values separately, while a union shares memory for all members. Changing one union member overwrites the others.
#include <stdio.h>
#include <string.h>
struct Person {
char name[20];
int age;
float height;
};
union Data {
int i;
float f;
char str[20];
};
int main() {
struct Person p1;
strcpy(p1.name, "Alice");
p1.age = 30;
p1.height = 5.5f;
printf("Structure Person:\n");
printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);
printf("Height: %.1f\n", p1.height);
union Data d;
d.i = 10;
printf("\nUnion Data after setting int: %d\n", d.i);
d.f = 220.5f;
printf("Union Data after setting float: %.1f\n", d.f);
strcpy(d.str, "Hello");
printf("Union Data after setting string: %s\n", d.str);
printf("\nNote: After setting string, int and float values are overwritten.\n");
return 0;
}Structures use more memory because they store all members separately.
Unions save memory by sharing space but only one member can be used at a time.
Accessing a union member that was not last set can give unexpected results.
Structures store all members separately and keep all data at once.
Unions share the same memory for all members, so only one value is stored at a time.
Use structures when you need to keep all data together, and unions when you want to save memory and only use one value at a time.