C 中的哈希 table,指针数组
Hash table in C, array of pointers
我正在尝试在 C 中实现哈希 table。
我们对值进行哈希处理,然后对 table 的大小取模以获得索引 i.
table 的每个条目都是一个链表。然后我们把这个值放到对应列表的第i个位置。
为此,我创建了一个结构列表:
struct list {
char val;
struct list *next;
}
所以一个空列表就是指针 NULL。
然后我需要创建我的结构 table :
struct hash_table {
uint32_t size;
struct list *index_table[];
}
现在我想创建一个大小为 N 的空哈希 table。为此我创建了一个函数:
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
。
- 立即删除结果被覆盖为
NULL
的额外malloc()
以消除内存泄漏。
- 使用
for
的正确语法:使用 ;
而不是 ,
。
- Return创建的对象。
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 */
}
我正在尝试在 C 中实现哈希 table。 我们对值进行哈希处理,然后对 table 的大小取模以获得索引 i.
table 的每个条目都是一个链表。然后我们把这个值放到对应列表的第i个位置。
为此,我创建了一个结构列表:
struct list {
char val;
struct list *next;
}
所以一个空列表就是指针 NULL。
然后我需要创建我的结构 table :
struct hash_table {
uint32_t size;
struct list *index_table[];
}
现在我想创建一个大小为 N 的空哈希 table。为此我创建了一个函数:
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
。 - 立即删除结果被覆盖为
NULL
的额外malloc()
以消除内存泄漏。 - 使用
for
的正确语法:使用;
而不是,
。 - Return创建的对象。
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 */
}