C Search records by key
Check whether a parcel is registered even if a driver has yet to be assigned.
A simple example
Search records by key
- Start with A = 2
- Do this Look for key A
- Result Present
Syntax
strcmp(entry.parcel, wanted) == 0
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonFind a parcel whose driver is still unassigned
A dispatch desk registers parcels before assigning drivers. Parcel P7 already has a record with an empty assignment, and the operator must distinguish it from a parcel that has never been registered.
#include <stdio.h>
#include <string.h>
int main(void) {
struct Delivery { const char *parcel; const char *driver; };
struct Delivery ledger[] = {{"P4", "Lee"}, {"P7", NULL}};
for (size_t i = 0; i < sizeof ledger / sizeof ledger[0]; ++i) {
if (strcmp(ledger[i].parcel, "P7") == 0) {
puts("Registered");
break;
}
}
return 0;
}
Registered
P7 appears in the register and the driver field is still unassigned.
Find an unassigned booking
A clinic already has booking B12, although a clinician has yet to be assigned. The desk checks whether the identifier has a record before creating one. Is the key already present?
Look for a second ticket
A counter has recorded ticket T2 and receives a query for T3. The desk checks whether the identifier has a record before creating one. Is the key already present?
What to watch for
Keep the key test separate from a null driver pointer. This small C ledger searches records sequentially.