C Array of Structures
In C, you can use arrays to store multiple instances of structures. This is particularly useful when dealing with a collection of related data, such as student records, employee details, or product inventories.
Why Use an Array of Structures?
- To group related data and organize it efficiently.
- To easily manage and access multiple records of the same type.
- To leverage indexing for quick data retrieval.
Syntax
The general syntax for an array of structures:
struct StructureName {
data_type member1;
data_type member2;
...
};
struct StructureName arrayName[array_size];
Example: Basic Array of Structures
Here's a basic example that demonstrates how to use an array of structures:
Example 1:
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[50];
float marks;
};
int main()
{
struct Student students[3];
// Assigning values
students[0].id = 1;
strcpy(students[0].name, "Alice");
students[0].marks = 85.5;
students[1].id = 2;
strcpy(students[1].name, "Bob");
students[1].marks = 92.0;
students[2].id = 3;
strcpy(students[2].name, "Charlie");
students[2].marks = 78.9;
// Displaying values
for (int i = 0; i < 3; i++) {
printf("Student ID: %d\n", students[i].id);
printf("Name: %s\n", students[i].name);
printf("Marks: %.2f\n\n", students[i].marks);
}
return 0;
}
Output:
Student ID: 1
Name: Alice
Marks: 85.50
Student ID: 2
Name: Bob
Marks: 92.00
Student ID: 3
Name: Charlie
Marks: 78.90
Name: Alice
Marks: 85.50
Student ID: 2
Name: Bob
Marks: 92.00
Student ID: 3
Name: Charlie
Marks: 78.90
Array of Structures with Functions
Using functions, you can make the code modular by passing the array of structures to a function for processing:
Example 2:
#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[50];
float salary;
};
void displayEmployees(struct Employee employees[], int size) {
for (int i = 0; i < size; i++) {
printf("Employee ID: %d\n", employees[i].id);
printf("Name: %s\n", employees[i].name);
printf("Salary: %.2f\n\n", employees[i].salary);
}
}
int main()
{
struct Employee employees[2];
// Assigning values
employees[0].id = 101;
strcpy(employees[0].name, "John");
employees[0].salary = 50000.5;
employees[1].id = 102;
strcpy(employees[1].name, "Jane");
employees[1].salary = 60000.7;
// Displaying values using a function
displayEmployees(employees, 2);
return 0;
}
Output:
Employee ID: 101
Name: John
Salary: 50000.50
Employee ID: 102
Name: Jane
Salary: 60000.70
Name: John
Salary: 50000.50
Employee ID: 102
Name: Jane
Salary: 60000.70
Key Points
- An array of structures allows you to store multiple records of the same type efficiently.
- Structures can be accessed using indexing and dot notation (e.g.,
array[index].member
). - Using functions with arrays of structures improves code modularity and readability.