C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
data_structures/hash_table/main.c
Go to the documentation of this file.
1/**
2 * @file main.c
3 * @brief Hash-table CLI demo — word frequency counter.
4 */
5
6#include "hash_table.h"
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10
11int main(int argc, char *argv[]) {
12 if (argc < 2) {
13 printf("Usage: %s <word1> <word2> ...\n", argv[0]);
14 printf("Counts occurrences of each word.\n");
15 printf("Example: %s the quick brown fox the lazy dog the\n", argv[0]);
16 return EXIT_FAILURE;
17 }
18
19 hash_table_t *ht = ht_create();
20 if (!ht) return EXIT_FAILURE;
21
22 for (int i = 1; i < argc; i++) {
23 int current = 0;
24 ht_get(ht, argv[i], &current);
25 if (!ht_set(ht, argv[i], current + 1)) {
26 fprintf(stderr, "out of memory\n");
27 ht_destroy(ht);
28 return EXIT_FAILURE;
29 }
30 }
31
32 printf("Counts (size=%zu, capacity=%zu):\n",
33 ht_size(ht), ht_capacity(ht));
34 for (int i = 1; i < argc; i++) {
35 int count = 0;
36 if (ht_get(ht, argv[i], &count)) {
37 printf(" %-20s %d\n", argv[i], count);
38 ht_remove(ht, argv[i]); /* dedup the printout */
39 }
40 }
41
42 ht_destroy(ht);
43 return EXIT_SUCCESS;
44}
int main(void)
Definition benchmark.c:50
size_t ht_capacity(const hash_table_t *ht)
Definition hash_table.c:123
bool ht_set(hash_table_t *ht, const char *key, int value)
Definition hash_table.c:77
bool ht_remove(hash_table_t *ht, const char *key)
Definition hash_table.c:107
hash_table_t * ht_create(void)
Definition hash_table.c:40
bool ht_get(const hash_table_t *ht, const char *key, int *out)
Definition hash_table.c:99
size_t ht_size(const hash_table_t *ht)
Definition hash_table.c:122
void ht_destroy(hash_table_t *ht)
Definition hash_table.c:50
Open-addressing string→int hash table with linear probing.