Visvesvaraya Technological University (VTU)
PG and SDC, Talakal
Programming and Problem Solving in C
(Course Code: MMC101)
Module-4: Structures And Unions
Department of MCA
C Programming — Module 4: Structures And Unions
Contents
1 Structure 2
2 Nested Structures 4
3 Pointers and Structures 6
4 Array of Structures 8
5 Self-Referential Structures 10
6 Dynamic Memory Allocation 11
7 Singly Linked List 14
8 typedef 16
9 Union 18
10 Storage Classes and Visibility 19
1
C Programming — Module 4: Structures And Unions
1. Structure
Introduction
In C programming, a structure is a powerful user-defined data type that enables the programmer
to combine variables of different data types under a single name. Structures are mainly used
when we want to represent a real-world entity that has multiple attributes of different types,
such as a student, employee, or bank account.
Definition
A structure in C is a user-defined data type that allows grouping related variables of different
data types into a single unit. Each variable inside a structure is called a member.
Syntax of Structure
1 struct structure_name {
2 data_type member1;
3 data_type member2;
4 data_type member3;
5 };
Explanation of Syntax
• struct is a keyword used to define a structure.
• structure_name is the name of the structure.
• Members can be of different data types.
• The structure definition ends with a semicolon.
Example of Structure
The following example defines a structure to store student information.
1 struct Student {
2 int roll;
3 char name[30];
4 float marks;
5 };
Program: Read and Display Student Information
1 #include <stdio.h>
2
2
C Programming — Module 4: Structures And Unions
3 struct Student {
4 int roll;
5 char name[30];
6 float marks;
7 };
8
9 int main() {
10 struct Student s;
11
12 printf("Enter Roll Number: ");
13 scanf("%d", &[Link]);
14
15 printf("Enter Name: ");
16 scanf("%s", [Link]);
17
18 printf("Enter Marks: ");
19 scanf("%f", &[Link]);
20
21 printf("\nStudent Details\n");
22 printf("Roll : %d\n", [Link]);
23 printf("Name : %s\n", [Link]);
24 printf("Marks : %.2f\n", [Link]);
25
26 return 0;
27 }
Output (Sample)
Enter Roll Number: 101
Enter Name: Rahul
Enter Marks: 85.5
Student Details
Roll : 101
Name : Rahul
Marks : 85.50
Accessing Structure Members
Structure members are accessed using the dot (.) operator.
1 [Link] = 10;
2 [Link] = 90.5;
3
C Programming — Module 4: Structures And Unions
Advantages of Structures
• Groups related data into a single unit.
• Simplifies data handling in programs.
• Enhances program clarity.
• Useful in arrays, functions, and file handling.
Applications of Structures
• Student and employee records.
• Banking and financial applications.
• Database management systems.
• Inventory and billing systems.
2. Nested Structures
A nested structure is a structure that contains another structure as one of its members. It allows
programmers to represent complex real-world entities in an organized and modular way.
Syntax
1 struct Structure1 {
2 data_type member1;
3 data_type member2;
4 };
5
6 struct Structure2 {
7 data_type memberA;
8 struct Structure1 memberB;
9 };
Explanation
In the above syntax:
• Structure1 is defined first.
• Structure2 contains an object of Structure1.
• Members of the inner structure are accessed using the dot (.) operator multiple times.
Example of Nested Structure
Consider a student record system where each student has personal details and a date of birth.
The date of birth itself consists of day, month, and year, which can be grouped into a separate
structure.
4
C Programming — Module 4: Structures And Unions
1 struct Date {
2 int day;
3 int month;
4 int year;
5 };
6
7 struct Student {
8 int roll;
9 char name[20];
10 struct Date dob;
11 };
Program Using Nested Structure
1 #include <stdio.h>
2
3 struct Date {
4 int day;
5 int month;
6 int year;
7 };
8
9 struct Student {
10 int roll;
11 char name[20];
12 struct Date dob;
13 };
14
15 int main() {
16 struct Student s;
17
18 printf("Enter Roll Number: ");
19 scanf("%d", &[Link]);
20
21 printf("Enter Name: ");
22 scanf("%s", [Link]);
23
24 printf("Enter Date of Birth (dd mm yyyy): ");
25 scanf("%d %d %d", &[Link], &[Link], &[Link]);
26
27 printf("\nStudent Details\n");
28 printf("Roll Number : %d\n", [Link]);
29 printf("Name : %s\n", [Link]);
30 printf("DOB : %d-%d-%d\n",
31 [Link], [Link], [Link]);
5
C Programming — Module 4: Structures And Unions
32
33 return 0;
34 }
Output (Sample)
Enter Roll Number: 101
Enter Name: Sachin
Enter Date of Birth (dd mm yyyy): 31 03 2003
Student Details
Roll Number : 101
Name : sachin
DOB : 31-3-2003
Advantages of Nested Structures
• Helps in organizing complex data logically.
• Improves code readability and maintainability.
• Represents real-world entities more accurately.
• Encourages modular programming.
3. Pointers and Structures
A pointer to a structure is a pointer variable that stores the address of a structure variable. Using
pointers with structures helps reduce memory overhead and improves program performance.
Syntax of Pointer to Structure
1 struct Student *ptr;
Accessing Structure Members Using Pointer
When a pointer points to a structure, its members are accessed using the arrow operator (->).
The expression ptr->member is equivalent to (*ptr).member.
1 ptr->roll;
2 (*ptr).roll;
6
C Programming — Module 4: Structures And Unions
Example
The following example demonstrates how a pointer is used to access structure members.
1 struct Student {
2 int roll;
3 char name[20];
4 };
Program: Pointer to Structure
1 #include <stdio.h>
2
3 struct Student {
4 int roll;
5 char name[20];
6 };
7
8 int main() {
9 struct Student s = {101, "Ayaan"};
10 struct Student *ptr = &s;
11
12 printf("Student Details\n");
13 printf("Roll : %d\n", ptr->roll);
14 printf("Name : %s\n", ptr->name);
15
16 return 0;
17 }
Output (Sample)
Student Details
Roll : 101
Name : Ayaan
Advantages of Using Pointers with Structures
• Reduces memory usage when passing structures to functions.
• Allows dynamic allocation of structures.
• Enables efficient data manipulation.
• Useful in linked lists, trees, and other data structures.
7
C Programming — Module 4: Structures And Unions
Applications
• Dynamic data structures such as linked lists.
• Database record handling.
• File handling and memory management.
• Large-scale software applications.
4. Array of Structures
An array of structures is a collection of structure variables of the same type stored under a
single array name. It allows efficient storage and processing of multiple records.
Syntax
1 struct structure_name array_name[size];
Example of Array of Structures
The following example declares an array of structures to store information of students.
1 struct Student {
2 int roll;
3 char name[20];
4 };
5
6 struct Student s[2];
Program: Array of Structures
1 #include <stdio.h>
2
3 struct Student {
4 int roll;
5 char name[20];
6 };
7
8 int main() {
9 struct Student s[2];
10 int i;
11
12 for(i = 0; i < 2; i++) {
13 printf("Enter Roll and Name: ");
14 scanf("%d %s", &s[i].roll, s[i].name);
8
C Programming — Module 4: Structures And Unions
15 }
16
17 printf("\nStudent Details\n");
18 for(i = 0; i < 2; i++) {
19 printf("Roll : %d Name : %s\n", s[i].roll, s[i].name);
20 }
21
22 return 0;
23 }
Output (Sample)
Enter Roll and Name: 101 Ayaan
Enter Roll and Name: 102 Sara
Student Details
Roll : 101 Name : Ayaan
Roll : 102 Name : Sara
Accessing Elements
Each element of the array is accessed using an index and the dot (.) operator.
1 s[0].roll = 101;
2 s[1].name = "Sara";
Advantages of Array of Structures
• Stores multiple records efficiently.
• Easy access using array index.
• Simplifies looping and data manipulation.
• Useful for database-like applications.
Applications
• Student and employee record management.
• Inventory and billing systems.
• Banking and library management software.
• Data processing applications.
9
C Programming — Module 4: Structures And Unions
5. Self-Referential Structures
A self-referential structure is a structure that contains a pointer to another structure of the
same type. This pointer is used to link multiple structure objects together.
Syntax of Self-Referential Structure
1 struct Node {
2 int data;
3 struct Node *next;
4 };
Explanation of Syntax
• data stores the actual information.
• next is a pointer that stores the address of another Node.
• The last node in the structure points to NULL.
Example Use Case
Self-referential structures are commonly used to implement linked lists. Each node contains
data and a pointer to the next node, forming a chain of nodes.
Program: Self-Referential Structure (Linked List Node)
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct Node {
5 int data;
6 struct Node *next;
7 };
8
9 int main() {
10 struct Node *head, *second, *third;
11
12 head = (struct Node *)malloc(sizeof(struct Node));
13 second = (struct Node *)malloc(sizeof(struct Node));
14 third = (struct Node *)malloc(sizeof(struct Node));
15
16 head->data = 10;
17 head->next = second;
18
10
C Programming — Module 4: Structures And Unions
19 second->data = 20;
20 second->next = third;
21
22 third->data = 30;
23 third->next = NULL;
24
25 printf("Linked List Elements:\n");
26 printf("%d %d %d\n", head->data, second->data, third->data);
27
28 return 0;
29 }
Output (Sample)
Linked List Elements:
10 20 30
Advantages of Self-Referential Structures
• Enables dynamic memory allocation.
• Allows efficient insertion and deletion.
• Optimizes memory usage.
• Forms the basis of linked lists, trees, and graphs.
Applications
• Linked lists.
• Stacks and queues.
• Trees and graphs.
• Memory management systems.
6. Dynamic Memory Allocation
Dynamic memory allocation is the process of allocating and deallocating memory during
program execution using predefined library functions provided by the standard header file
stdlib.h.
Dynamic Memory Allocation Functions
C provides the following four library functions for dynamic memory management:
• malloc()
• calloc()
11
C Programming — Module 4: Structures And Unions
• realloc()
• free()
malloc() Function
The malloc() function allocates a single block of memory of specified size and returns a
pointer to the allocated memory.
Syntax:
1 ptr = (data_type *)malloc(size_in_bytes);
Example:
1 int *ptr = (int *)malloc(sizeof(int));
calloc() Function
The calloc() function allocates memory for multiple elements and initializes all allocated
memory to zero.
Syntax:
1 ptr = (data_type *)calloc(n, size_of_each_element);
Example:
1 int *ptr = (int *)calloc(5, sizeof(int));
realloc() Function
The realloc() function is used to change the size of previously allocated memory without
losing existing data.
Syntax:
1 ptr = (data_type *)realloc(ptr, new_size);
Example:
1 ptr = (int *)realloc(ptr, 10 * sizeof(int));
free() Function
The free() function releases dynamically allocated memory back to the system.
Syntax:
1 free(ptr);
12
C Programming — Module 4: Structures And Unions
Program: Dynamic Memory Allocation Example
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main() {
5 int *ptr;
6 int i, n = 5;
7
8 ptr = (int *)malloc(n * sizeof(int));
9
10 if(ptr == NULL) {
11 printf("Memory allocation failed\n");
12 return 1;
13 }
14
15 for(i = 0; i < n; i++) {
16 ptr[i] = (i + 1) * 10;
17 }
18
19 printf("Allocated values:\n");
20 for(i = 0; i < n; i++) {
21 printf("%d ", ptr[i]);
22 }
23
24 free(ptr);
25 return 0;
26 }
Advantages of Dynamic Memory Allocation
• Efficient use of memory.
• Memory can be allocated and deallocated as required.
• Supports dynamic data structures.
• Reduces memory wastage.
Disadvantages
• Memory leaks if free() is not used properly.
• More complex than static allocation.
• Slower compared to static memory allocation.
13
C Programming — Module 4: Structures And Unions
7. Singly Linked List
A singly linked list is a linear data structure in which each node contains data and a pointer
that points to the next node in the sequence. The last node points to NULL, indicating the end
of the list.
Structure of a Node
Each node of a singly linked list consists of:
• Data field to store the information.
• Link field to store the address of the next node.
Syntax of Node Structure
1 struct Node {
2 int data;
3 struct Node *next;
4 };
Working of Singly Linked List
• The list is accessed using a pointer called head.
• Each new node is created using dynamic memory allocation.
• The next pointer links one node to the next.
• Traversal is performed by following the next pointers until NULL.
Program: Creation and Traversal of Singly Linked List
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct Node {
5 int data;
6 struct Node *next;
7 };
8
9 int main() {
10 struct Node *head = NULL, *temp, *newNode;
11 int choice = 1;
12
13 while(choice) {
14 newNode = (struct Node *)malloc(sizeof(struct Node));
15
14
C Programming — Module 4: Structures And Unions
16 if(newNode == NULL) {
17 printf("Memory allocation failed\n");
18 return 1;
19 }
20
21 printf("Enter data: ");
22 scanf("%d", &newNode->data);
23 newNode->next = NULL;
24
25 if(head == NULL) {
26 head = temp = newNode;
27 } else {
28 temp->next = newNode;
29 temp = newNode;
30 }
31
32 printf("Add another node (1/0): ");
33 scanf("%d", &choice);
34 }
35
36 printf("\nSingly Linked List:\n");
37 temp = head;
38 while(temp != NULL) {
39 printf("%d -> ", temp->data);
40 temp = temp->next;
41 }
42 printf("NULL\n");
43
44 return 0;
45 }
Output (Sample)
Enter data: 10
Add another node (1/0): 1
Enter data: 20
Add another node (1/0): 1
Enter data: 30
Add another node (1/0): 0
Singly Linked List:
10 -> 20 -> 30 -> NULL
15
C Programming — Module 4: Structures And Unions
Advantages of Singly Linked List
• Dynamic size.
• Efficient insertion and deletion.
• No memory wastage due to contiguous storage.
• Easy implementation using pointers.
Disadvantages
• Sequential access only.
• Extra memory required for pointer storage.
• Reverse traversal is not possible.
Applications
• Implementation of stacks and queues.
• Dynamic memory management.
• Polynomial and expression manipulation.
• Operating system scheduling.
8. typedef
typedef is a keyword in C used to define an alias name for an existing data type. It does not
create a new data type but provides an alternative name for an existing one.
General Syntax
1 typedef existing_data_type new_name;
Using typedef with Structure
One of the most common uses of typedef is with structures, which allows structure variables
to be declared without using the struct keyword repeatedly.
1 typedef struct {
2 int x;
3 int y;
4 } Point;
Program Using typedef
16
C Programming — Module 4: Structures And Unions
1 #include <stdio.h>
2
3 typedef struct {
4 int x;
5 int y;
6 } Point;
7
8 int main() {
9 Point p = {10, 20};
10
11 printf("x = %d\n", p.x);
12 printf("y = %d\n", p.y);
13
14 return 0;
15 }
Output (Sample)
x = 10
y = 20
typedef with Basic Data Types
1 typedef unsigned int uint;
2 uint a = 25;
Advantages of typedef
• Makes complex declarations easier to understand.
• Improves code clarity.
• Reduces programming errors.
• Enhances portability of code.
Applications of typedef
• Simplifying structure declarations.
• Defining custom data types.
• Improving readability in large programs.
• Used in system and library programming.
17
C Programming — Module 4: Structures And Unions
9. Union
A union is a user-defined data type in which all members share a common memory location.
The size of a union is equal to the size of its largest member.
Syntax of Union
1 union union_name {
2 data_type member1;
3 data_type member2;
4 data_type member3;
5 };
Example of Union
1 union Data {
2 int i;
3 float f;
4 char ch;
5 };
Program: Union Demonstration
1 #include <stdio.h>
2
3 union Data {
4 int i;
5 float f;
6 };
7
8 int main() {
9 union Data d;
10
11 d.i = 10;
12 printf("Integer value: %d\n", d.i);
13
14 d.f = 3.14;
15 printf("Float value : %.2f\n", d.f);
16
17 return 0;
18 }
18
C Programming — Module 4: Structures And Unions
Output (Sample)
Integer value: 10
Float value : 3.14
Working of Union
• All members share the same memory space.
• Assigning a value to one member overwrites the value of the previous member.
• Only the most recently assigned member holds a valid value.
Difference Between Structure and Union
Structure Union
Each member has separate memory All members share same memory
Multiple members can be used simultaneously Only one member can be used at a time
Size is sum of member sizes Size is max of member sizes
More memory usage Less memory usage
Advantages of Union
• Efficient memory utilization.
• Useful in memory-constrained systems.
• Simplifies representation of variant data.
Disadvantages
• Only one member can be accessed at a time.
• No type safety.
• May lead to data loss if misused.
Applications of Union
• Embedded systems programming.
• Memory management.
• Communication protocols.
• Implementing variant records.
10. Storage Classes and Visibility
A storage class in C specifies the scope (where a variable can be accessed), lifetime (how long
it exists in memory), and visibility (which parts of the program can use it) of a variable or
19
C Programming — Module 4: Structures And Unions
function.
Types of Storage Classes
C provides four primary storage classes:
• auto
• static
• extern
• register
auto Storage Class
• Default storage class for local variables.
• Scope is limited to the block in which it is declared.
• Lifetime exists only during function execution.
• Memory is allocated on the stack.
1 void fun() {
2 auto int x = 10;
3 }
static Storage Class
• Preserves the value of a variable between function calls.
• Scope is local to the block or file.
• Lifetime is throughout the program execution.
• Memory is allocated only once.
Program: static Storage Class
1 #include <stdio.h>
2
3 void count() {
4 static int c = 0;
5 c++;
6 printf("%d\n", c);
7 }
8
9 int main() {
10 count();
11 count();
12 return 0;
13 }
20
C Programming — Module 4: Structures And Unions
extern Storage Class
• Used to declare a global variable defined in another file.
• Provides global visibility across multiple source files.
• Does not allocate memory.
1 extern int total;
register Storage Class
• Requests the compiler to store variable in CPU register.
• Faster access compared to memory variables.
• Address operator (&) cannot be used.
1 register int i;
Visibility and Scope
• Local scope: Variables accessible only within a function or block.
• Global scope: Variables accessible throughout the program.
• File scope: Variables accessible within a single source file.
Comparison of Storage Classes
Storage Class Scope Lifetime Default Value
auto Block Function execution Garbage
static Block/File Entire program Zero
extern Global Entire program Zero
register Block Function execution Garbage
Advantages of Storage Classes
• Better control over variable lifetime.
• Efficient memory management.
• Improved program organization.
21