Skip to content

Structure, Union & Typedef

A structure in C is a collection of variables (called members) of different data types grouped together under one name.

Advantages of Structures:

  • Handles complex data easily.
  • Groups different data types logically.
  • Useful in real-world applications like databases.

Disadvantages:

  • Cannot directly compare two structures using ==.
  • Takes more memory than arrays (because of padding).
#include <stdio.h>
#include <string.h>
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
struct Student s;
s.roll = 1;
strcpy(s.name, "Akash");
s.marks = 92.5;
printf("Roll: %d\nName: %s\nMarks: %.2f\n", s.roll, s.name, s.marks);
return 0;
}

A union is similar to a structure but uses shared memory for all its members.

  • Only one member can hold a value at a time.
  • Size of union = size of largest member.
  • memory = size of largest member.

Advantages of Union:

  • Memory efficient (used in embedded systems).
  • Useful for interpreting the same memory differently.

Disadvantages:

  • Only one member can be used at a time.
  • Risk of data overwrite.
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("i: %d\n", d.i);
d.f = 220.5; // overwrites i
printf("f: %.2f\n", d.f);
return 0;
}

Memory Layout:

  • Structure: memory = sum of all members (with padding).
  • Union: memory = size of largest member.

typedef is used to create a new name (alias) for an existing data type.

Advantages of typedef:

  • Makes code shorter and readable.
  • Useful for portability (changing data types easily).
#include <stdio.h>
typedef unsigned int uint;
typedef struct {
int id;
char name[50];
} Student;
int main() {
uint age = 25;
Student s = {101, "Shruti"};
printf("Age: %u, Name: %s\n", age, s.name);
return 0;
}

Real-World Applications:

  • Structures – Database records (students, employees).
  • Unions – Device drivers, protocol headers, embedded systems.
  • typedef – Portable code for operating systems and libraries.