【发布时间】:2020-07-14 21:43:30
【问题描述】:
有哈希表的def
typedef struct pair
{
char* key;
int value;
}pair;
typedef struct node
{
pair* p;
struct node* next;
}node;
node* hash_table[HASH_SIZE]; /*pointer to Hash Table*/
还有init_data的实现
void init_data()
{
int i;
for (i = 0; i < HASH_SIZE; i++)
{
hash_table[i]->p = (pair*)malloc(sizeof(pair));
if (hash_table[i]->p == NULL)
printf("Error: in index %d ", i);
hash_table[i]->p->key = NULL;
hash_table[i]->p->value = 0;
}
curr_size = 0;
}
然后编译器向我发送这条消息 de-reference NULL 指针 为什么?
【问题讨论】:
-
错误发生在哪一行?
-
你的哈希表是一个指针
node*,但你没有用malloc初始化它。当您执行hash_table[i]->p时,就会发生错误。 -
@MatheusPortela 但是
hash_table不是全局声明为任何数组node* hash_table[HASH_SIZE];吗? -
你从未为
hash_table[i]分配任何内存。 -
@ArdentCoder 在提供的代码中,
hash_table是node*的数组。数组本身hash_table已初始化,但其元素hash_table[i](node*类型)尚未初始化。然后,使用hash_table[i]->p取消引用会引发错误,因为hash_table[i]是NULL。
标签: c pointers segmentation-fault hashtable