Hashing converts a key into an integer, then reduces it to a valid index with % size. Storing a key at that index means you can find it later by recomputing the same index, without scanning. Because many keys share a few slots, a complete table also needs collision handling.
Remember
unsigned slot = hash(key) % TABLE_SIZE;
table[slot] = key; /* store */
if (table[slot] == key) ... /* find */
Reference
Cheat Sheet
Keep these facts handy while you work with Hashing Basics in C.
Topic
Detail
Hash
Key to integer
Index
hash % size
Lookup
O(1) average
Collision
Two keys, one slot
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Hash Functions.
Example 1 — Store and look up keys
A table of ten slots, four keys, no collisions.
C
#include <stdio.h>
#define SIZE 10
int main(void) {
int table[SIZE];
int keys[] = {15, 28, 37, 41};
for (int i = 0; i < SIZE; i++) table[i] = -1;
for (int i = 0; i < 4; i++) {
int slot = keys[i] % SIZE;
table[slot] = keys[i];
printf("%d -> slot %d\n", keys[i], slot);
}
int look = 37;
int s = look % SIZE;
printf("lookup %d: %s\n", look, table[s] == look ? "found" : "missing");
return 0;
}