只是想做一种哈希表,每个节点都是一个链表。
初始化空间时遇到问题,我做错了什么?
#include <stdlib.h>
typedef struct entry {
struct entry *next;
void *theData;
} Entry;
typedef struct HashTable {
Entry **table;
int size;
} HashTable;
int main(){
HashTable *ml;
ml = initialize();
return 0;
}
HashTable *initialize(void)
{
HashTable *p;
Entry **b;
int i;
if ((p = (HashTable *)malloc(sizeof(HashTable *))) == NULL)
return NULL;
p->size = 101;
if ((b = (Entry **)malloc(p->size * sizeof(Entry **))) == NULL)
return NULL;
p->table = b;
for(i = 0; i < p->size; i++) {
Entry * b = p->table[i];
b->theData = NULL;
b->next = NULL;
}
return p;
}
最佳答案
您需要将 sizeof(HashTable*)
更改为 sizeof(HashTable)
并且同样将 sizeof(Entry **)
更改为 sizeof(条目 *)
。第二件事是对于每个 Entry
,您需要在循环内再次使用 malloc
分配内存。
关于c - 为什么这个 malloc 在 C 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023098/