Writing the Search function
What you'll learn: How to locate a specific record in your data store by iterating through memory and comparing strings.
The Needle in the Haystack
Now that your data store can hold multiple records, you need a way to find a specific one. Think of your data store like a filing cabinet. To find a specific file, you start at the first drawer and check the label. If it’s not the one you want, you move to the next.
In C, this is a linear search. Since our data store is an array of structs, we will loop through each entry and compare the "key" (like a username or ID) against the search term provided by the user.
Using strcmp()
To compare the search term with the data in memory, we use the strcmp function from the <string.h> library. Remember: strcmp returns 0 if two strings are an exact match.
We also need to handle the possibility that the item doesn't exist. Our function should return a pointer to the found record, or NULL if we reach the end of our data without a match.
Implementing the Search
Here is how you might structure a search function for a store containing a User struct:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[50];
int id;
} User;
// search returns a pointer to the User if found, otherwise NULL
User* find_user(User* database, int current_count, char* search_name) {
for (int i = 0; i < current_count; i++) {
// Compare the search_name to the name in the current record
if (strcmp(database[i].name, search_name) == 0) {
printf("Record found at index %d\n", i);
return &database[i]; // Return the address of the match
}
}
printf("Record not found.\n");
return NULL;
}
Why Return a Pointer?
Returning a pointer (User*) is more efficient than returning the entire struct. If your struct grows to hold hundreds of fields, returning the actual data would force C to copy all that information. By returning a pointer, you are simply handing over the "address" of where the data lives in your existing array, allowing your program to read or update it directly.
Key takeaway
A search function loops through your array and uses strcmp to find a match, returning a pointer to the specific memory location of the record.