C Hashing Basics

Intermediate
6 min read
Updated: Nov 2026
1 example

Mapping Keys to Slots

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  */

Cheat Sheet

Keep these facts handy while you work with Hashing Basics in C.

TopicDetail
HashKey to integer
Indexhash % size
LookupO(1) average
CollisionTwo keys, one slot

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;
}

How It Works

  1. -1 marks an empty slot.
  2. Lookup recomputes 37 % 10 = 7 and checks one slot only.
  3. No loop over the table is needed.

Edge Cases & Pitfalls

Check these before relying on Hashing Basics in real programs.

coll

Ignoring collisions

Keys 15 and 25 both map to slot 5 here; the second would overwrite the first.

sentinel

Sentinel clashes

If -1 can be a real key, choose another empty marker.

Key Takeaways

  • Compute, then index.
  • Same key, same slot.
  • Collisions need a plan.

One line: Hashing converts a key into an integer, then reduces it to a valid index with % size.

Frequently Asked Questions

A hash function converts a key to a number; taking it modulo the table size gives the array index where the key is stored.
Because the slot is computed directly from the key instead of searching.
Continue with "C Hash Functions" next. Compare a character-sum hash with a polynomial hash. The C Hash Tables hub lists every topic in order.

Next: Hash Functions

Compare a character-sum hash with a polynomial hash.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful