Library contents

C Key-value records and strcmp

Update a shelf count and retrieve it using the product label.

A simple example

Key-value records and strcmp

  1. Start with A = 1
  2. Do this Store 2 at key A
  3. Result A = 2
Looking up the same key now returns the new value.

Syntax

C syntax
strcmp(stock[i].key, product) == 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
./lesson

Update the count for a shelf label

A shop keeps one inventory entry for each shelf label. After a second delivery arrives, the clerk replaces the old tea count and looks up the current total using the same label.

From the programstruct Entry stock[] = {{"Rice", 2}, {"Tea", 3}}
Result7
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    struct Entry { const char *key; int count; };
    struct Entry stock[] = {{"Rice", 2}, {"Tea", 3}};
    for (size_t i = 0; i < sizeof stock / sizeof stock[0]; ++i) {
        if (strcmp(stock[i].key, "Tea") == 0) {
            stock[i].count = 7;
            printf("%d\n", stock[i].count);
            break;
        }
    }
    return 0;
}
Output
7

Updating the Tea key changes the recorded count from three to seven.

Advertisements

Revise a locker assignment

A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?

Givengreen → 6, then green → 9
Worked result9

Correct a menu price

A café changes its soup price after reprinting the menu. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?

Givensoup → 5, then soup → 6
Worked result6

What to watch for

C17 has no built-in map. A linear scan of records suits a small shelf register. Compare string contents with strcmp.

Documentation for Key-value records and strcmp