Search code examples
cstringstructhashtable

Creating a hash table with >1byte keys and values in C


I am trying to create a hash table in C from scratch. Here is a hash table with 1 byte (char*) keys and values I want to make, except I want my hash table to store keys and values as strings up to 32 characters long (char key[32], char value[32]). Here is my struct:

#define KV_SIZE 32

typedef struct hash_entry{
    char key[KV_SIZE];
    char value[KV_SIZE];
    struct hash_entry* next;
} hash_entry;

I am having trouble forming a function called create_entry() because I don't know how to assign my struct strings, key and value, to values.

// create an entry
hash_entry* create_entry(char key[KV_SIZE], char value[KV_SIZE]){
    printf("%s\n", key);
    hash_entry* entry = (hash_entry*)malloc(sizeof(hash_entry*));

    // I want entry->key and entry->value to store a string up to 32 chars long
    strncpy(entry->key, key, strlen(key)); // Error
    strncpy(entry->value, value, strlen(value)); // Error

    entry->next = NULL;

    return entry;
}

So far, it seems like I need my entry's to remain declared as pointers (hash_entry* entry) and not non-pointers (hash_entry entry) to be able to link them later.


Solution

  • Here's what fixed my code:

    hash_entry* create_entry(char key[HASH_SIZE], char value[HASH_SIZE]){
        // No casting needed and don't use sizeof(pointer)
        // use sizeof(hash_entry) to get the full size of your struct
        hash_entry* entry = malloc(sizeof(hash_entry));
    
        // aside: don't forget to check the size of your strings
        if(strlen(key) < KV_SIZE && strlen(value) < KV_SIZE){
            // use strcpy instead of strncpy
            strcpy(entry->key, key);
            strcpy(entry->value, value);
            entry->next = NULL;
    
            return entry;
        }
        return NULL;
    }