在 C 中使用 >1 字节的键和值创建散列 table

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

我正在尝试从头开始在 C 中创建哈希 [​​=29=]。 Here is a hash table with 1 byte (char*) keys and values 我想创建,但我希望我的散列 table 将键和值存储为最多 32 个字符长的字符串 (char key[32], char value[32])。这是我的 struct:

#define KV_SIZE 32

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

我在构造一个名为 create_entry() 的函数时遇到问题,因为我不知道如何将我的 struct 字符串、键和值分配给值。

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

到目前为止,似乎我需要我的 entry 保持声明为指针 (hash_entry* entry) 而不是非指针 (hash_entry entry) 才能 link他们稍后。

hash_entry* entry = (hash_entry*)malloc(sizeof(hash_entry));

修复我的代码的方法如下:

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