A Structure is like a suitcase with separate compartments for your shoes, clothes, and toiletries. You can carry everything at the same time.
A Union is like a magic box that can only hold one item at a time. If you put your shoes in, the clothes have to come out.
1. Structures (
struct)#include <stdio.h> #include <string.h> struct Student { char name[20]; int id; float gpa; }; int main() { struct Student s1; // Assigning values strcpy(s1.name, "Alice"); s1.id = 101; s1.gpa = 3.8; printf("--- Structure Output ---\n"); printf("Name: %s\n", s1.name); printf("ID: %d\n", s1.id); printf("GPA: %.2f\n", s1.gpa); return 0; }
Expected Output:
--- Structure Output ---
Name: Alice
ID: 101
GPA: 3.802. Unions (union)
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d1;
// Warning: Only one member can hold a value at a time!
d1.i = 10;
printf("--- Union Output ---\n");
printf("After setting i: %d\n", d1.i);
d1.f = 220.5;
printf("After setting f: %.1f\n", d1.f);
// Notice that 'i' is now corrupted because 'f' took its place
printf("Value of i now: %d (Corrupted!)\n", d1.i);
return 0;
}Expected Output:
--- Union Output ---
After setting i: 10
After setting f: 220.5
Value of i now: 1130135552 (Corrupted!)