6.2) Array of structures in C
An array of structures in C is a collection of multiple structure instances, where each instance holds related data.
This allows you to work with multiple sets of structured data efficiently.
Let’s explore array of structures with simple explanations and code examples:
Table of Contents
Defining an Array of Structures
To define an array of structures, you use the same syntax as defining an array of any other data type.
You provide the structure name followed by the array name and size.
Example: Defining an Array of Structures
#include <stdio.h>
struct Student {
char name[50];
int roll;
float marks;
};
int main() {
// Declare an array of 'Student' structures
struct Student students[3];
// Assign values to each structure instance
strcpy(students[0].name, "Alice");
students[0].roll = 101;
students[0].marks = 85.5;
strcpy(students[1].name, "Bob");
students[1].roll = 102;
students[1].marks = 78.0;
strcpy(students[2].name, "Carol");
students[2].roll = 103;
students[2].marks = 92.3;
// Print details of each student
for (int i = 0; i < 3; i++) {
printf("Student %d:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll: %d\n", students[i].roll);
printf("Marks: %.2f\n\n", students[i].marks);
}
return 0;
}
Output:
Student 1:
Name: Alice
Roll: 101
Marks: 85.50
Student 2:
Name: Bob
Roll: 102
Marks: 78.00
Student 3:
Name: Carol
Roll: 103
Marks: 92.30
Initializing an Array of Structures
You can initialize an array of structures while declaring it, using curly braces.
Example: Initializing an Array of Structures
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
// Initialize an array of 'Point' structures
struct Point points[3] = {{1, 2}, {3, 4}, {5, 6}};
for (int i = 0; i < 3; i++) {
printf("Point %d: (%d, %d)\n", i + 1, points[i].x, points[i].y);
}
return 0;
}
Output:
Point 1: (1, 2)
Point 2: (3, 4)
Point 3: (5, 6)
Accessing Array of Structures
You can access the members of an array of structures using the dot (.
) operator.
Example: Accessing Array of Structures
#include <stdio.h>
struct Product {
char name[50];
float price;
};
int main() {
struct Product products[2];
strcpy(products[0].name, "Laptop");
products[0].price = 999.99;
strcpy(products[1].name, "Phone");
products[1].price = 399.99;
printf("Product 1:\n");
printf("Name: %s\n", products[0].name);
printf("Price: %.2f\n\n", products[0].price);
printf("Product 2:\n");
printf("Name: %s\n", products[1].name);
printf("Price: %.2f\n", products[1].price);
return 0;
}
Output:
Product 1:
Name: Laptop
Price: 999.99
Product 2:
Name: Phone
Price: 399.99
Using arrays of structures allows you to work with collections of related data efficiently. They’re particularly useful when you need to manage multiple instances of structured data, such as student records, employee details, or product information.