Array of Structures in C Language
Introduction
In C programming, structures allow you to group variables of different types under a single name. This is particularly useful for organizing complex data. An array of structures is an array where each element is a structure. This is useful when you need to manage multiple records of the same structure.
Defining a Structure
Before creating an array of structures, you need to define a structure. Here is an example of defining a structure for a student:
struct Student { char name[50]; int rollNumber; float marks; };
Creating an Array of Structures
Once you have defined a structure, you can create an array of that structure. Here is how you can create an array of 5 students:
struct Student students[5];
Accessing Elements of an Array of Structures
You can access elements of an array of structures using the array index and dot operator. Here is an example:
students[0].rollNumber = 1; strcpy(students[0].name, "John Doe"); students[0].marks = 95.5;
Example Program
Below is a complete program that demonstrates how to use an array of structures to store and display information about students.
#include <stdio.h> #include <string.h> // Define the structure struct Student { char name[50]; int rollNumber; float marks; }; int main() { // Create an array of 3 students struct Student students[3]; // Initialize the first student's data students[0].rollNumber = 1; strcpy(students[0].name, "John Doe"); students[0].marks = 95.5; // Initialize the second student's data students[1].rollNumber = 2; strcpy(students[1].name, "Jane Smith"); students[1].marks = 89.0; // Initialize the third student's data students[2].rollNumber = 3; strcpy(students[2].name, "Emily Davis"); students[2].marks = 92.3; // Display the students' information for (int i = 0; i < 3; i++) { printf("Student %d:\n", i + 1); printf(" Name: %s\n", students[i].name); printf(" Roll Number: %d\n", students[i].rollNumber); printf(" Marks: %.2f\n\n", students[i].marks); } return 0; }
Output
Student 1: Name: John Doe Roll Number: 1 Marks: 95.50 Student 2: Name: Jane Smith Roll Number: 2 Marks: 89.00 Student 3: Name: Emily Davis Roll Number: 3 Marks: 92.30
Conclusion
Arrays of structures allow you to efficiently manage collections of related data in C. By using structures, you can group different data types under a single name, and an array of structures enables you to handle multiple records easily. This concept is widely used in various applications, such as managing student records, employee details, and more.