gpt4 book ai didi

c - 哈希表中的段错误 - C

转载 作者:行者123 更新时间:2023-11-30 14:41:05 24 4
gpt4 key购买 nike

我目前正在为类做一项编程作业。我的一个函数出现段错误,但无法找到问题的根源。我已经尽力了,发现seg错误发生在“if(myNode->key==key)”。任何明智的话语都会有所帮助!

struct node*searchForPerson(const char *value){
int key=convertToKey(value);
struct node *myNode;

int i=0;
int j = (key % 8)+(i*(key%5));


while (i < size - 1 && hashTable[j].head != NULL && hashTable[j].index != key ) {
i++;
j=(key % 8)+(i*(key%5));
}
myNode=hashTable[j].head;

if(myNode->key==key) {

printf(" found\n");
return myNode;
}
else{
printf("not found\n");
return NULL;
}
}

我认为问题的根源可能是我插入哈希函数:

void insertToHash(int key,  char *value){

int i = 0;
int j = (key % 8)+(i*(key%5));
struct node *newnode = createNode(key, value);
/*head of list for the bucket with index "hashIndex"*/
if (!hashTable[j].head) {
hashTable[j].head = newnode;
hashTable[j].count=1;
return;
}

while (i < size - 1 && hashTable[j].head != NULL) {
i++;
j=(key % 8)+(i*(key%5));
}
//adding new node to the list
hashTable[j].head=newnode;
hashTable[j].count++;
return;



hashTable[j].head = newnode;
hashTable[j].count++;
}

最佳答案

您应该添加一条 if 语句,以确保 hashTable[j].head 不为 NULL

请记住,您的 while 循环条件是对 3 个条件进行 AND 运算,因此如果其中任何一个变为 false,循环就会退出。特别是,在循环之后,您不知道它是否退出,因为

  1. i 现在大于或等于 size - 1
  2. hashTable[j].head 现在等于 NULL
  3. hashTable[j].index 现在等于 key

如果情况是 (2),则 myNode 将为 NULL,因此 myNode->key 将取消引用空指针,从而导致出现段错误。

关于c - 哈希表中的段错误 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com