Implementing the bucket array
What you'll learn: How to create the backbone of a hash table by using an array of pointers to store multiple elements at the same index.
The Post Office Analogy
Imagine a post office with 100 mailboxes. Usually, one mailbox belongs to one person. But what happens if two people have the same mailbox number? In a hash table, this is a "collision."
Instead of making the mailbox a tiny slot that only fits one envelope, we turn each mailbox into a bucket. Each bucket is actually a hook where we can hang a bag. If five people share mailbox #42, we just put five envelopes into that one bag. In C, we implement these "bags" using Linked Lists.
Defining the Structure
To build a bucket array, we don't store data directly in the array. Instead, we store a pointer to a node. If a slot is empty, the pointer is NULL. If it’s occupied, it points to the first piece of data. If another piece of data lands in the same slot, we attach it to the first one like a chain.
First, define your node, then define the table which holds the array:
#include <stdio.h>
#include <stdlib.h>
// 1. Define the node (the "envelope" in the bag)
typedef struct Node {
char *key;
int value;
struct Node *next; // Points to the next item in the same bucket
} Node;
// 2. Define the Hash Table
typedef struct {
int size;
Node **buckets; // An array of pointers to Nodes
} HashTable;
HashTable* create_table(int size) {
HashTable *table = malloc(sizeof(HashTable));
table->size = size;
// Allocate memory for the array of pointers
table->buckets = calloc(table->size, sizeof(Node*));
return table;
}
Why use pointers?
By using Node **buckets, we are creating an array of "Head Pointers." Each index in our array acts as the start of a linked list. When we want to look up a key, we hash it to find the index, then walk through that specific linked list until we find our target.
This setup ensures that no matter how many items share an index (a collision), our table can handle them without overwriting data or crashing.
Key takeaway
A bucket array is an array of linked list pointers that allows a single index to store multiple items through chaining.