![]() |
VOOZH | about |
In C, a struct (short for structure) is a user-defined data type that allows us to combine data items of different kinds. An array of structs is an array in which each element is of struct type. In this article, we will learn how to search for a specific element in an array of structs.
Example:
Input:
Person people[3] = { { "Alice", 25 }, { "Bob", 30 }, { "Charlie", 35 } };
searchPerson = "Bob"
Output:
Person found! Name: Bob, Age: 30
To search in an array of structs in C, iterate through each element of the array and compare the search key with the relevant field of each struct. If a match is found, return the index of that element. If no match is found, return a negative value such as -1.
Student with ID 2 is Jane
Time Complexity: O(n)
Space Complexity: O(1)