// Array of structs
// The most common “associative array” pattern in C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *key;
int value;
} Pair;
int cmp(const void *a, const void *b) {
return strcmp(((Pair*)a)->key, ((Pair*)b)->key);
}
int main() {
Pair items[] = {
{"apple", 5},
{"banana", 10},
{"orange", 15},
{"strawberries", 20}
};
int size = sizeof(items) / sizeof(items[0]);
Pair key = {"orange", 0};
Pair *found = bsearch(&key, items, size, sizeof(Pair), cmp);
if (found)
printf("Found: %s = %d\n", found->key, found->value);
}
/*
run:
Found: orange = 15
*/