Open In App

How to Search in Array of Struct in C?

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

Searching in an Array of Struct in C

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.

C Program to Search in Array of Struct




// C Program to search in array of struct
#include <stdio.h>
#include <string.h>
  
// Define the struct
typedef struct {
    int id;
    char name[50];
} Student;
  
int main()
{
    // Array of struct declaration
    Student students[]
        = { { 1, "John" }, { 2, "Jane" }, { 3, "Jim" } };
  
    // ID to search
    int searchId = 2;
  
    // Searching in the array of struct
    int i;
    for (i = 0; i < 3; i++) {
        if (students[i].id == searchId) {
            printf("Student with ID %d is %s\n", searchId,
                   students[i].name);
            break;
        }
    }
  
    if (i == 3) {
        printf("No student found with ID %d\n", searchId);
    }
  
    return 0;
}

Output

Student with ID 2 is Jane

Time Complexity: O(n)
Space Complexity: O(1)

Article Tags :