我正在尝试将一个整数插入哈希表。为此,我正在创建一个node *'s数组,并且试图使像listarray[i]->data=5
这样的赋值成为可能。但是,我仍然对指针感到非常困惑,并且在注释“ // crashes here”的行上崩溃了,我也不明白为什么。我在main()中的初始化是否无效?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node * next;
} node;
//------------------------------------------------------------------------------
void insert (node **listarray, int size)
{
node *temp;
int value = 11; //just some random value for now, eventually will be scanned in
int index = value % size; // 11 modulo 8 yields 3
printf ("index is %d\n", index); //prints 3 fine
if (listarray[index] == NULL)
{
printf("listarray[%d] is NULL",index); //prints because of loop in main
listarray[index]->data = value; //crashes here
printf("listarray[%d] is now %d",index,listarray[index]->data); //never prints
listarray[index]->next = NULL;
}
else
{
temp->next = listarray[index];
listarray[index] = temp;
listarray[index]->data = value;
}
}//end insert()
//------------------------------------------------------------------------------
int main()
{
int size = 8,i; //set default to 8
node * head=NULL; //head of the list
node **listarray = malloc (sizeof (node*) * size); //declare an array of Node *
//do i need double pointers here?
for (i = 0; i < size; i++) //malloc each array position
{
listarray[i] = malloc (sizeof (node) * size);
listarray[i] = NULL; //satisfies the first condition in insert();
}
insert(*&listarray,size);
}
输出:
index is 3
listarray[3] is NULL
(崩溃)
所需的输出:
index is 3
listarray[3] is NULL
listarray[3] is now 11
最佳答案
这里有很多问题:
如果您具有某个特定size
的哈希表,则该哈希码必须映射到0
和size - 1
之间的值。默认大小为8,但哈希码为x % 13
,这意味着索引可能超出范围。
您的insert
函数还应该传递要插入的项目(除非该参数称为size
,在这种情况下,其名称会严重错误)。
if (listarray[index] == NULL) {
listarray[index]->data = value; //crashes here
listarray[index]->next = NULL;
}
难怪它会崩溃:当节点为
NULL
时,您无法使用*
或->
取消引用它。您应该在这里分配新的内存。而且您不应该在这里分配内存:
for (i = 0; i < size; i++) //malloc each array position
{
listarray[i] = malloc (sizeof (node) * size);
listarray[i] = NULL; //satisfies the first condition in insert();
}
分配内存,然后将其重置为
NULL
是胡说八道。 NULL
是一个特殊值,表示指向的位置没有内存。只需将所有节点设置为NULL
,这意味着哈希表开始时没有任何节点。在需要某个位置的节点时分配。在
else
子句中,您可以编写: else
{
temp->next = listarray[index];
listarray[index] = temp;
listarray[index]->data = value;
}
但是
temp
尚未分配,但是您取消引用它。这和取消引用NULL一样糟糕。您的哈希表还需要一种处理冲突的方法。看起来好像在哈希表中的每个索引处都有一个链表。这是处理它的好方法,但是您没有正确实现它。
您似乎在理解指针方面有问题。也许您应该从一个简单的数据结构(如链表)入手,以进行练习?牢牢掌握这一点之后,就可以使用所学的知识来实现哈希表。
关于c - 插入哈希表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26442924/