In real-life problems, we often need to store different kinds of information together β for example, a student's name (string), roll number (integer), and marks (float). C provides a feature called a Structure to group such related data items of different types under one name. Similarly, Unions are another feature that help save memory when only one of the members is used at a time.

A Structure is a user-defined data type that allows you to combine variables of different types. Itβs useful for representing complex data like students, employees, or products.
struct structure_name {
data_type member1;
data_type member2;
...
};
Example:
#include <stdio.h>
struct Student {
int roll;
char name[30];
float marks;
};
int main() {
struct Student s1 = {101, "Ravi", 89.5};
printf("Roll: %d\\n", s1.roll);
printf("Name: %s\\n", s1.name);
printf("Marks: %.2f\\n", s1.marks);
return 0;
}
Use the . (dot operator) to access individual members of a structure.
s1.roll = 102;
strcpy(s1.name, "Asha");
s1.marks = 92.3;
printf("%s scored %.1f marks", s1.name, s1.marks);
We can create multiple records of the same type using arrays of structures.
struct Student s[3] = {
{1, "Ravi", 88.5},
{2, "Meena", 91.0},
{3, "Ajay", 79.5}
};
for(int i = 0; i < 3; i++)
printf("%d %s %.1f\\n", s[i].roll, s[i].name, s[i].marks);
struct Date {
int day, month, year;
};
struct Student {
int roll;
char name[30];
struct Date dob; // nested structure
};
struct Student s1 = {101, "Ravi", {12, 5, 2004}};
printf("DOB: %d-%d-%d", s1.dob.day, s1.dob.month, s1.dob.year);
void display(struct Student s) {
printf("%d %s %.1f\\n", s.roll, s.name, s.marks);
}
int main() {
struct Student s1 = {101, "Ravi", 88.5};
display(s1);
}
struct Student s1 = {101, "Ravi", 88.5};
struct Student *ptr = &s1;
printf("%s", ptr->name); // use arrow operator (->)
ptr->member instead of (*ptr).member for easy access.
A Union is similar to a structure, but it shares the same memory location for all members. Only one member can contain a value at a time β making it memory-efficient.
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d1;
d1.i = 10;
printf("i = %d\\n", d1.i);
d1.f = 22.5;
printf("f = %.1f\\n", d1.f);
strcpy(d1.str, "Hello");
printf("str = %s\\n", d1.str);
return 0;
}
| Feature | Structure | Union |
|---|---|---|
| Memory | Separate memory for each member | Shared memory for all members |
| Usage | All members can store values simultaneously | Only one member holds a value at a time |
| Size | Sum of all member sizes | Size of the largest member |
| Example | Student info (roll, marks) | Value that may change type (int/float/string) |
. and -> operators to access members.