In C, while working with an array of structs we have to iterate through each struct in an array to perform certain operations or access its members. In this article, we will learn how to iterate through an array of the structs in C.
Iterate Over of an Array of Structures
To iterate through an array of the structures in C, we can simply use a loop (for loop or a while loop) and access each struct in the array using the array indexing, and then we can access every member using the member name.
C Program to Iterate Over an Array of Structs
The below example demonstrates how we can iterate through an array of structs and access each struct in C.
// C program to illustrate how to iterate through array of // structs #include <stdio.h> // Define the Person struct struct Person {
int id;
char name[20];
int age;
}; int main()
{ // Creating and initializing an array of Person structs
struct Person people[] = { { 1, "Ram" , 20 },
{ 2, "Mohan" , 25 },
{ 3, "Ria" , 30 } };
// Calculating the number of elements in the array of
// struct
int numPeople = sizeof (people) / sizeof (people[0]);
// Iterating through the array of structs
for ( int i = 0; i < numPeople; i++) {
printf ( "Person Id: %d, Name: %s, Age: %d\n" ,
people[i].id, people[i].name, people[i].age);
}
return 0;
} |
Person Id: 1, Name: Ram, Age: 20 Person Id: 2, Name: Mohan, Age: 25 Person Id: 3, Name: Ria, Age: 30
Time Complexity: O(N), here n is the number of elements in the array of structs.
Auxilliary Space: O(1)
Note: We can also use a pointer to iterate through the array and access each element’s members using the arrow operator (
->
).