首页 > 解决方案 > 在 C 中创建具有 >1byte 键和值的哈希表

问题描述

我正在尝试从头开始在 C 中创建一个哈希表。这是一个带有char*char key[32], char value[32]1字节(这是我的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的 's 保持声明为指针 ( hash_entry* entry) 而不是非指针 ( hash_entry entry) 以便以后能够链接它们。

标签: cstringstructhashtable

解决方案


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

推荐阅读