Module 8: Structures and Unions in C
Learning Objectives
By the end of this module, you will be able to:
- Understand what structures and unions are.
- Create and use structures to store related data.
- Work with nested structures.
- Create arrays of structures.
- Access structure members using pointers.
- Understand the difference between structures and unions.
- Use
typedefto simplify data type declarations. - Define constants using
enum. - Build practical applications such as student, employee, and library management systems.
Introduction
So far, you've worked with basic data types such as:
intfloatchardouble
These data types store only one type of value.
But imagine you need to store information about a student:
- Roll Number
- Name
- Age
- Percentage
Using separate variables becomes difficult.
1int roll; 2char name[50]; 3int age; 4float percentage;
What if there are 500 students?
This is where structures become useful.
Structures allow you to group multiple variables of different data types under a single name.
What is a Structure?
A structure is a user-defined data type that groups related variables of different data types.
Example:
1Student 2 3Roll Number 4Name 5Age 6Percentage
Instead of creating four separate variables repeatedly, we create one structure.
Structure Syntax
1struct StructureName 2{ 3 data_type member1; 4 data_type member2; 5 data_type member3; 6};
Example
1struct Student 2{ 3 int roll; 4 char name[50]; 5 float marks; 6};
Creating Structure Variables
1struct Student student1;
Multiple variables
1struct Student student1, student2, student3;
Accessing Structure Members
Members are accessed using the dot (.) operator.
Example
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 char name[30]; 7 float marks; 8}; 9 10int main() 11{ 12 struct Student student; 13 14 student.roll = 101; 15 student.marks = 92.5; 16 17 printf("%d\n", student.roll); 18 printf("%.2f", student.marks); 19 20 return 0; 21}
Output
1101 292.50
Reading Structure Data
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 char name[30]; 7 float marks; 8}; 9 10int main() 11{ 12 struct Student student; 13 14 printf("Enter Roll Number: "); 15 scanf("%d", &student.roll); 16 17 printf("Enter Name: "); 18 scanf("%29s", student.name); 19 20 printf("Enter Marks: "); 21 scanf("%f", &student.marks); 22 23 printf("\nStudent Details\n"); 24 printf("Roll: %d\n", student.roll); 25 printf("Name: %s\n", student.name); 26 printf("Marks: %.2f\n", student.marks); 27 28 return 0; 29}
Nested Structures
A structure can contain another structure as one of its members.
Example
1#include <stdio.h> 2 3struct Address 4{ 5 char city[30]; 6 char state[30]; 7}; 8 9struct Student 10{ 11 int roll; 12 char name[30]; 13 struct Address address; 14}; 15 16int main() 17{ 18 struct Student student = {101, "Ankit", {"Delhi", "Delhi"}}; 19 20 printf("Name: %s\n", student.name); 21 printf("City: %s\n", student.address.city); 22 23 return 0; 24}
Output
1Name: Ankit 2City: Delhi
Array of Structures
Arrays of structures are used to store multiple records.
Example
1struct Student students[100];
Program
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 char name[30]; 7}; 8 9int main() 10{ 11 struct Student students[2]; 12 13 for(int i = 0; i < 2; i++) 14 { 15 printf("Enter Roll and Name: "); 16 scanf("%d %29s", &students[i].roll, students[i].name); 17 } 18 19 printf("\nStudent List\n"); 20 21 for(int i = 0; i < 2; i++) 22 { 23 printf("%d %s\n", students[i].roll, students[i].name); 24 } 25 26 return 0; 27}
Pointer to Structure
Pointers can point to structures.
Declaration
1struct Student *ptr;
Accessing Members
There are two ways.
Using dereferencing
1(*ptr).roll
Using the arrow operator
1ptr->roll
The arrow operator (->) is easier to read and commonly used.
Example
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 char name[20]; 7}; 8 9int main() 10{ 11 struct Student student = {101, "Ankit"}; 12 13 struct Student *ptr = &student; 14 15 printf("%d\n", ptr->roll); 16 printf("%s\n", ptr->name); 17 18 return 0; 19}
Output
1101 2Ankit
What is a Union?
A union is a user-defined data type similar to a structure.
The key difference is that all members of a union share the same memory location.
Only one member can store a meaningful value at a time.
Union Syntax
1union Data 2{ 3 int number; 4 float price; 5 char letter; 6};
Structure vs Union
| Structure | Union |
|---|---|
| Each member has its own memory | All members share the same memory |
| Larger memory usage | Smaller memory usage |
| All members can contain valid values simultaneously | Only one member should be used at a time |
| Used for records | Used for memory optimization |
Union Example
1#include <stdio.h> 2 3union Data 4{ 5 int number; 6 float price; 7}; 8 9int main() 10{ 11 union Data data; 12 13 data.number = 100; 14 printf("%d\n", data.number); 15 16 data.price = 45.5f; 17 printf("%.2f\n", data.price); 18 19 return 0; 20}
Assigning a new value to one union member overwrites the previous member because they share the same memory.
typedef
The typedef keyword creates an alias (alternate name) for an existing data type.
Without typedef
1struct Student student;
With typedef
1typedef struct 2{ 3 int roll; 4 char name[30]; 5} Student; 6 7Student student;
Advantages
- Shorter code
- Improved readability
- Easier maintenance
enum (Enumeration)
An enumeration is a user-defined data type consisting of named integer constants.
Example
1enum Day 2{ 3 MONDAY, 4 TUESDAY, 5 WEDNESDAY, 6 THURSDAY, 7 FRIDAY, 8 SATURDAY, 9 SUNDAY 10};
Values assigned automatically
1MONDAY = 0 2TUESDAY = 1 3WEDNESDAY = 2 4...
Custom Enum Values
1enum Status 2{ 3 SUCCESS = 1, 4 FAILED = 0, 5 PENDING = 2 6};
Example
1#include <stdio.h> 2 3enum Status 4{ 5 SUCCESS = 1, 6 FAILED = 0 7}; 8 9int main() 10{ 11 enum Status result = SUCCESS; 12 13 printf("%d", result); 14 15 return 0; 16}
Output
11
Practice Project 1: Student Database
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 char name[30]; 7 float marks; 8}; 9 10int main() 11{ 12 struct Student students[3]; 13 14 for(int i = 0; i < 3; i++) 15 { 16 printf("Enter Roll, Name and Marks: "); 17 scanf("%d %29s %f", 18 &students[i].roll, 19 students[i].name, 20 &students[i].marks); 21 } 22 23 printf("\nStudent Records\n"); 24 25 for(int i = 0; i < 3; i++) 26 { 27 printf("%d %s %.2f\n", 28 students[i].roll, 29 students[i].name, 30 students[i].marks); 31 } 32 33 return 0; 34}
Practice Project 2: Employee Record
1#include <stdio.h> 2 3typedef struct 4{ 5 int id; 6 char name[30]; 7 float salary; 8} Employee; 9 10int main() 11{ 12 Employee employee; 13 14 printf("Enter Employee ID: "); 15 scanf("%d", &employee.id); 16 17 printf("Enter Name: "); 18 scanf("%29s", employee.name); 19 20 printf("Enter Salary: "); 21 scanf("%f", &employee.salary); 22 23 printf("\nEmployee Details\n"); 24 printf("ID: %d\n", employee.id); 25 printf("Name: %s\n", employee.name); 26 printf("Salary: %.2f\n", employee.salary); 27 28 return 0; 29}
Practice Project 3: Library Management
1#include <stdio.h> 2 3typedef struct 4{ 5 int bookId; 6 char title[50]; 7 char author[50]; 8} Book; 9 10int main() 11{ 12 Book book; 13 14 printf("Enter Book ID: "); 15 scanf("%d", &book.bookId); 16 17 getchar(); // Clear newline left by scanf 18 19 printf("Enter Title: "); 20 fgets(book.title, sizeof(book.title), stdin); 21 22 printf("Enter Author: "); 23 fgets(book.author, sizeof(book.author), stdin); 24 25 printf("\nLibrary Record\n"); 26 printf("Book ID: %d\n", book.bookId); 27 printf("Title: %s", book.title); 28 printf("Author: %s", book.author); 29 30 return 0; 31}
Common Mistakes to Avoid
- Forgetting the semicolon (
;) after a structure or union definition. - Using the dot (
.) operator instead of the arrow (->) when working with a pointer to a structure. - Accessing uninitialized structure members.
- Expecting all union members to hold valid values simultaneously.
- Forgetting to include enough space for character arrays in structures.
- Mixing
scanf()andfgets()without handling the leftover newline.
Best Practices
- Use structures to group logically related data.
- Use arrays of structures to manage collections of records.
- Prefer
typedeffor cleaner and more readable code. - Use
enuminstead of hard-coded integer constants to improve readability. - Use the arrow operator (
->) when accessing members through pointers. - Choose a union only when you need memory optimization and only one member is active at a time.
- Initialize structure variables before use.
Module Summary
In this module, you learned:
- What structures are and how they group related data of different types.
- How to declare, initialize, and access structure members.
- How to create nested structures and arrays of structures.
- How to work with pointers to structures using the
->operator. - How unions differ from structures and when to use them.
- How
typedefsimplifies type declarations. - How
enumcreates readable named constants. - How to apply these concepts by building a student database, an employee record system, and a simple library management application.
After completing this module, you'll be ready to learn File Handling in C, including reading and writing files, binary files, file positioning, error handling, and building real-world applications such as student record systems and data storage utilities.