How to Iterate Through Array of Structs in C?
source link: https://www.geeksforgeeks.org/how-to-iterate-through-array-of-structs-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Iterate Through Array of Structs in C?
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 (
->
).
Here's a complete roadmap for you to become a developer: Learn DSA -> Master Frontend/Backend/Full Stack -> Build Projects -> Keep Applying to Jobs
And why go anywhere else when our DSA to Development: Coding Guide helps you do this in a single program! Apply now to our DSA to Development Program and our counsellors will connect with you for further guidance & support.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK