Skip over navigation

Hash Tables

Coding up a Hash Table


Coding up a Hash Table, page 2

page 1 of 2

Let's implement a hash table in C. We'll write a hash table that stores strings, and to handle collisions we'll use separate chaining.

Data structures

First we define our data structures

1. We begin with our linked lists (for separate chaining):

typedef struct _list_t_ {
    char *string;
    struct _list_t_ *next;
} list_t;

2. Now we need a hash table structure.

typedef struct _hash_table_t_ {
    int size;       /* the size of the table */
    list_t **table; /* the table elements */
} hash_table_t;
Why did we declare the table as list_t **table? We don't know up front how big we want the table to be. Therefore, we need to make the table a dynamic array. Remember that an array is just a big block of memory and is basically synonymous with a pointer (see the SparkNotes on arrays and pointers. What we have is a pointer to a pointer to a linked list; thus list_t **table.


What basic operations do we need to be able to perform with our hash tables?: 1) We need to be able to create a table. 2) We need to be able to hash; thus we need a hash function. 3) We need to be able to free a table. 4) We need to be able to insert into them. 5) We need to be able to lookup an element in them. That should do it for a basic implementation.

1. Creation. We need to be able to create a hash table, something like:

hash_table_t *my_hash_table;
int size_of_table = 12;
my_hash_table = create_hash_table(size_of_table);
The creation function might look something like this:

hash_table_t *create_hash_table(int size)
    hash_table_t *new_table;
    if (size<1) return NULL; /* invalid size for table */

    /* Attempt to allocate memory for the table structure */
    if ((new_table = malloc(sizeof(hash_value_t))) == NULL) {
        return NULL;
    /* Attempt to allocate memory for the table itself */
    if ((new_table->table = malloc(sizeof(list_t *) * size)) == NULL) {
        return NULL;

    /* Initialize the elements of the table */
    for(i=0; i<size; i++) new_table->table[i] = NULL;

    /* Set the table's size */
    new_table->size = size;

    return new_table;

Follow Us