【问题标题】:Creating a hash table with >1byte keys and values in C在 C 中创建具有 >1 字节键和值的哈希表
【发布时间】:2020-08-24 14:39:51
【问题描述】:

我正在尝试从头开始在 C 中创建一个哈希表。 Here is a hash table with 1 byte (char*) keys and values 我想做,但我希望我的哈希表将键和值存储为最长 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) 以便以后能够链接它们。

【问题讨论】:

  • 至少大小是错误的(指针大小)。为避免该错误entry = (hash_entry*)malloc(sizeof(hash_entry*)); ---> entry = malloc(sizeof *entry);(不需要强制转换,不使用类型)
  • @chux-ReinstateMonica 摆脱我对 malloc() 的强制转换似乎有效......
  • 希望我能在发布答案之前看到这些 cmets。我的道歉。如果您所做的all 只是删除了演员表,那么稍后会出现另一个问题。删除强制转换并将 sizeof 更改为 malloc 调用中的正确类型
  • 使用strncpy很少是正确的,这段代码使用它的方式肯定是错误的。您需要检查 strlen 返回的数字是否小于 32。如果是,请使用 strcpy。如果没有,那么您需要处理错误。要么中止程序,要么干脆拒绝添加条目。
  • @BryanHeden 我这样做了,我的代码运行了,但输出有一些额外的随机字符,所以我也将 strncpy 切换到 strcpy,然后它们就消失了。

标签: c string struct hashtable


【解决方案1】:

以下是修复我的代码的原因:

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

【讨论】:

    【解决方案2】:
    hash_entry* entry = (hash_entry*)malloc(sizeof(hash_entry));
    

    【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2010-10-15
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    相关资源
    最近更新 更多