Chapter 10 – Structures and Unions in C Language
Introduction
So far, we have learned about variables, arrays, strings, functions, and pointers. Arrays allow us to store multiple values of the same data type. But sometimes a program needs to store different types of information about a single object.
For example, information about a student may include:
Student ID – integer
Name – character array
Marks – floating-point value
Grade – character
Using separate variables for every student can make a program difficult to manage.
C provides structures to group related data of different types under one name.
C also provides unions, which are similar to structures but use memory differently.
In this chapter, you will learn:
Structures
Structure declaration
Structure variables
Structure members
Arrays of structures
Structures with functions
Pointers to structures
Nested structures
Unions
Difference between structures and unions
1. What is a Structure?
A structure is a user-defined data type that allows related variables of different data types to be grouped together.
Example
Suppose we want to store student information.
struct Student { int rollNo; char name[50]; float marks; };
Here, Student contains three different types of information:
Student ├── rollNo → int ├── name → char array └── marks → float
A structure is useful when different pieces of information belong to the same entity.
2. Structure Syntax
The general syntax is:
struct structure_name { data_type member1; data_type member2; data_type member3; };
Example:
struct Employee { int id; char name[50]; float salary; };
The semicolon after the closing brace is required.
3. Declaring Structure Variables
After defining a structure, we can declare variables of that structure type.
struct Student student1;
Here:
Student is the structure type.
student1 is a structure variable.
Multiple structure variables can also be declared:
struct Student student1, student2;
4. Accessing Structure Members
The dot operator . is used to access members of a structure variable.
Example:
student1.rollNo student1.name student1.marks
Complete Example
#include <stdio.h> struct Student { int rollNo; char name[50]; float marks; }; int main() { struct Student student1; student1.rollNo = 101; student1.marks = 85.5f; printf("Roll No = %d\n", student1.rollNo); printf("Marks = %.2f\n", student1.marks); return 0; }
Output
Roll No = 101 Marks = 85.50
5. Initializing a Structure
A structure can be initialized when the variable is declared.
struct Student student1 = { 101, "Rahul", 85.5f };
The values are assigned to members in the order in which the members are declared.
6. Complete Structure Example
#include <stdio.h> struct Student { int rollNo; char name[50]; float marks; }; int main() { struct Student student1 = { 101, "Rahul", 85.5f }; printf("Roll No: %d\n", student1.rollNo); printf("Name: %s\n", student1.name); printf("Marks: %.2f\n", student1.marks); return 0; }
Output
Roll No: 101 Name: Rahul Marks: 85.50
7. Taking Structure Data from the User
Structure members can be filled using input functions.
#include <stdio.h> struct Student { int rollNo; char name[50]; float marks; }; int main() { struct Student student; printf("Enter roll number: "); scanf("%d", &student.rollNo); printf("Enter name: "); scanf("%49s", student.name); printf("Enter marks: "); scanf("%f", &student.marks); printf("\nStudent Details\n"); printf("Roll No: %d\n", student.rollNo); printf("Name: %s\n", student.name); printf("Marks: %.2f\n", student.marks); return 0; }
8. Array of Structures
Sometimes we need to store information about many students.
Instead of declaring:
struct Student student1; struct Student student2; struct Student student3;
we can create an array of structures:
struct Student students[3];
Now the array contains three structure variables.
9. Example of an Array of Structures
#include <stdio.h> struct Student { int rollNo; char name[50]; float marks; }; int main() { struct Student students[3] = { {101, "Aman", 82.5f}, {102, "Riya", 91.0f}, {103, "Karan", 76.5f} }; int i; for(i = 0; i < 3; i++) { printf("Roll No: %d\n", students[i].rollNo); printf("Name: %s\n", students[i].name); printf("Marks: %.2f\n\n", students[i].marks); } return 0; }
Output
Roll No: 101 Name: Aman Marks: 82.50 Roll No: 102 Name: Riya Marks: 91.00 Roll No: 103 Name: Karan Marks: 76.50
10. Structures and Functions
Structures can be passed to functions.
Example:
#include <stdio.h> struct Student { int rollNo; char name[50]; float marks; }; void display(struct Student s) { printf("Roll No: %d\n", s.rollNo); printf("Name: %s\n", s.name); printf("Marks: %.2f\n", s.marks); } int main() { struct Student student = {101, "Aman", 88.5f}; display(student); return 0; }
Here, the complete structure value is passed to the function.
11. Pointer to a Structure
A pointer can point to a structure variable.
Example:
struct Student student; struct Student *ptr; ptr = &student;
Now ptr stores the address of student.
12. Accessing Structure Members Through a Pointer
There are two ways to access a structure member through a pointer.
Method 1
(*ptr).rollNo
Method 2
Using the arrow operator:
ptr->rollNo
The arrow operator is generally more convenient.
13. Structure Pointer Example
#include <stdio.h> struct Student { int rollNo; float marks; }; int main() { struct Student student = {101, 90.5f}; struct Student *ptr = &student; printf("Roll No: %d\n", ptr->rollNo); printf("Marks: %.2f\n", ptr->marks); return 0; }
Output
Roll No: 101 Marks: 90.50
14. Nested Structures
A structure can contain another structure as a member.
Example:
struct Date { int day; int month; int year; }; struct Student { int rollNo; char name[50]; struct Date birthDate; };
Here, Student contains another structure called Date.
15. Nested Structure Example
#include <stdio.h> struct Date { int day; int month; int year; }; struct Student { int rollNo; char name[50]; struct Date birthDate; }; int main() { struct Student student = { 101, "Aman", {15, 8, 2010} }; printf("Name: %s\n", student.name); printf("Date of Birth: %d-%d-%d\n", student.birthDate.day, student.birthDate.month, student.birthDate.year); return 0; }
Output
Name: Aman Date of Birth: 15-8-2010
16. typedef with Structures
The typedef keyword can make structure declarations shorter.
Without typedef:
struct Student { int rollNo; float marks; }; struct Student s1;
Using typedef:
typedef struct { int rollNo; float marks; } Student; Student s1;
Now Student can be used directly as the type name.
17. What is a Union?
A union is a user-defined data type similar to a structure, but all its members share the same memory location.
Example:
union Data { int number; float price; char grade; };
A union can contain different types of members, but only one member's stored value should be considered active at a time.
18. Union Example
#include <stdio.h> union Data { int number; float price; }; int main() { union Data data; data.number = 100; printf("Number = %d\n", data.number); data.price = 25.5f; printf("Price = %.2f\n", data.price); return 0; }
The second assignment uses the same storage, so the previously stored number value should no longer be treated as the active union member.
19. Structure vs Union
The main difference is how memory is allocated for their members.
Structure
Each member has its own storage.
Structure +---------+---------+---------+ | int | float | char | +---------+---------+---------+
Members can hold their values simultaneously.
Union
Members share storage.
Union +---------------------------+ | Shared memory | +---------------------------+ ↑ ↑ ↑ int float char
Only one member's stored value should be treated as active at a time.
20. Difference Between Structure and Union
| Feature | Structure | Union |
|---|---|---|
| Memory | Separate storage for members | Shared storage |
| Members | Can hold values simultaneously | One active stored value at a time |
| Size | Generally accommodates all members plus possible padding | Large enough for its largest member plus possible alignment |
| Use | Group related information | Save memory when alternatives share storage |
21. Finding Structure Size
The sizeof operator can be used to determine the size of a structure object.
Example:
#include <stdio.h> struct Student { int rollNo; char name[20]; float marks; }; int main() { struct Student student; printf("Size = %zu bytes", sizeof(student)); return 0; }
The exact size may vary between systems because compilers can add padding for memory alignment.
22. Structure Assignment
Structure variables of the same structure type can be assigned to one another.
Example:
#include <stdio.h> struct Student { int rollNo; float marks; }; int main() { struct Student s1 = {101, 85.5f}; struct Student s2; s2 = s1; printf("Roll No: %d\n", s2.rollNo); printf("Marks: %.2f\n", s2.marks); return 0; }
Output
Roll No: 101 Marks: 85.50
23. Structure with an Array Member
A structure can contain an array.
Example:
struct Student { int rollNo; char name[50]; int marks[5]; };
Here, each student can have five marks stored inside the structure.
Example initialization:
struct Student s = { 101, "Aman", {80, 85, 90, 78, 88} };
24. Structure with Pointer Member
A structure can also contain pointers.
Example:
struct Data { int number; int *ptr; };
The pointer member can store the address of another integer object.
25. Structure and Dynamic Memory
Structures are frequently used together with dynamically allocated memory.
For example, a pointer to a structure can be created:
struct Student *ptr;
Memory can later be allocated for the structure using dynamic memory functions such as malloc().
Dynamic memory allocation will be discussed in a later chapter.
26. Real-World Applications of Structures
Structures are useful for representing real-world entities.
Student
Student ├── Roll Number ├── Name ├── Marks └── Grade
Employee
Employee ├── ID ├── Name ├── Department └── Salary
Product
Product ├── Product ID ├── Name ├── Price └── Quantity
Structures allow related information to be grouped logically.
27. Structure Pointer and ->
When a pointer points to a structure, the arrow operator -> is used to access its members.
Example:
struct Employee { int id; float salary; }; int main() { struct Employee employee = {101, 25000.0f}; struct Employee *ptr = &employee; printf("%d\n", ptr->id); printf("%.2f\n", ptr->salary); return 0; }
The following two expressions are equivalent:
ptr->id
and:
(*ptr).id
28. Structure Array with Loop
An array of structures can be processed using loops.
#include <stdio.h> struct Employee { int id; float salary; }; int main() { struct Employee employees[3] = { {101, 25000.0f}, {102, 30000.0f}, {103, 28000.0f} }; int i; for(i = 0; i < 3; i++) { printf("ID: %d, Salary: %.2f\n", employees[i].id, employees[i].salary); } return 0; }
Output
ID: 101, Salary: 25000.00 ID: 102, Salary: 30000.00 ID: 103, Salary: 28000.00
29. Common Mistakes with Structures and Unions
Mistake 1: Forgetting the struct keyword
If typedef has not been used, the structure type is normally declared as:
struct Student s;
not simply:
Student s;
unless Student has been defined as a typedef name.
Mistake 2: Using . with a structure pointer
Incorrect:
ptr.id
Correct:
ptr->id
when ptr is a pointer to a structure.
Mistake 3: Assuming union members retain separate values
Union members share storage. Writing to one member can change the stored representation of another member.
Mistake 4: Ignoring array limits inside structures
If a structure contains a character array, the input should respect the available capacity.
30. Quick Revision
| Concept | Meaning |
|---|---|
| Structure | Groups related variables of different types |
| Member | Variable inside a structure |
| . | Accesses member through a structure object |
| -> | Accesses member through a structure pointer |
| Array of Structures | Stores multiple structure objects |
| Nested Structure | Structure containing another structure |
| typedef | Creates an alternative type name |
| Union | Members share the same storage |
| sizeof | Determines object size in bytes |
31. Practice MCQs
Question 1
Which keyword is used to define a structure in C?
A. class
B. record
C. struct
D. object
Answer: C. struct
Question 2
Which operator is used to access a member of a structure variable?
A. ->
B. .
C. :
D. ::
Answer: B. .
Question 3
Which operator is used to access a structure member through a pointer?
A. .
B. ->
C. &
D. *
Answer: B. ->
Question 4
What is the main feature of a union?
A. All members have separate storage
B. Members share storage
C. It can contain only integers
D. It cannot contain different data types
Answer: B. Members share storage
Question 5
Which keyword can be used to create a shorter name for a structure type?
A. define
B. typedef
C. rename
D. alias
Answer: B. typedef
Question 6
Which operator can be used to determine the size of a structure object?
A. length
B. size
C. sizeof
D. sizeof()
Answer: C. sizeof
32. Programming Exercises
Try writing C programs to:
Create a structure to store student details.
Create a structure to store employee details.
Input and display information using a structure.
Create an array of five student structures.
Find the student with the highest marks.
Create a structure containing an array of marks.
Pass a structure to a function.
Pass a structure pointer to a function.
Create a nested structure for student and date information.
Create a structure using typedef.
Demonstrate the difference between a structure and a union.
Create an array of employee structures and display employees whose salary is above a specified value.
33. Key Points to Remember
A structure groups related data of different types.
Structure members can have different data types.
The . operator accesses members through a structure variable.
The -> operator accesses members through a structure pointer.
Arrays of structures can store information about multiple objects.
Structures can contain arrays, pointers, and other structures.
typedef can provide a convenient name for a structure type.
A union stores all members in shared memory.
Only one union member's stored value should normally be treated as active at a time.
sizeof can be used to determine the size of a structure or union object.
Structures are widely used to model real-world entities and organize complex data.
Chapter Summary
Structures allow programmers to combine related data of different types into a single logical unit. They are especially useful for representing entities such as students, employees, products, and customers.
Unions are similar to structures but use shared storage for their members. They can be useful when several possible data representations occupy the same memory area.
Structures, pointers, arrays, and functions can be combined to create powerful and organized C programs. These concepts also form the foundation for more advanced data structures and systems programming.
Next Chapter
Chapter 11 – File Handling in C Language
In the next chapter, you will learn how C programs can create, open, read, write, append, and close files, along with important file modes and standard file-handling functions.