【发布时间】: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,然后它们就消失了。