如何解决C中的哈希表,指针数组
我正在尝试用 C 实现一个哈希表。 我们对值进行散列,然后对表的大小进行取模以获得索引 i。
表的每个条目都是一个链表。然后我们把值放在对应列表中的 i 位置。
为此,我通过创建一个结构列表来进行排序:
struct list {
char val;
struct list *next;
}
所以一个空列表就是指针 NULL。
然后我需要创建我的结构表:
struct hash_table {
uint32_t size;
struct list *index_table[];
}
现在我想创建一个大小为 N 的空哈希表。为此我创建了一个函数:
struct hash_table* createTable(N) {
struct hash_table* table = malloc(sizeof(struct hash_table));
table->size = N;
for (int i=0,i<N,i++) {
table->index_table[i] = malloc(sizeof(struct list))) ;
table-> index_table[i] = NULL /*Empty list*/;
}
}
但是我从 valgrind 得到关于大小为 8 的无效读取的错误...
感谢您的帮助。 我仍然是 C 的初学者,所以任何想法都可能会有所帮助。
解决方法
你应该
- 指定函数参数的类型。
- 为数组
index_table
分配。 - 立即删除额外的
malloc()
,其结果被覆盖为NULL
以消除内存泄漏。 - 对
for
使用正确的语法:使用;
而不是,
。 - 返回创建的对象。
struct hash_table* createTable(uint32_t N) { /* specify the type of argument */
/* add size of the table */
struct hash_table* table = malloc(sizeof(struct hash_table) + sizeof(table->index_table[0]) * N);
table->size = N;
for (uint32_t i=0; i<N; i++) { /* use correct for syntax */
/* remove malloc() that is causing memory leak */
table-> index_table[i] = NULL /*Empty list*/;
}
return table; /* return what is created */
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。