gpt4 book ai didi

c - 哈希表中的段错误

转载 作者:行者123 更新时间:2023-11-30 16:36:11 25 4
gpt4 key购买 nike

我试图实现一个存储英语单词的哈希表。简而言之,我使用了一个链表数组(Chaining),我没有制作整个程序,只是实现了它需要一个单词输入并通过哈希表搜索它但它开始给我段错误。请帮我解决这个问题......预先感谢您!

strcpy(new->s,val);

这是我遇到段错误的地方。

我的整个代码:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

typedef struct node
{
string s;
struct node *next;
}node;

node* create(char*);

unsigned long sdbm(unsigned char*);

bool search(string s,node *first)
{
node *ptr=first;
bool found=false;

while(ptr->next!=NULL)
{
if(strcmp(ptr->s,s)==0)
{
found=true;
break;
}

}

if(found==true)
return true;
else
return false;
}



int main(void)
{
node a[26];
printf("Enter the string\n");
string s=get_string();
unsigned long hashcode = sdbm((unsigned char*)s);
printf("The hashcode is %lu\n", hashcode);

a[hashcode].next=create(s);

printf("Enter the string to be searched among the ones you recently typed
in\n");
string t=get_string();

if(search(t,&a[sdbm((unsigned char*)t)]) == true)
printf("found\n");
else
printf("not found\n");

}


node* create(string val)
{
node* new = malloc(sizeof(node));
if(new!=NULL)
{
new->s="";

strcpy(new->s,val); // this is the part ehere I get Segmentation Fault
new->next=NULL;
}

return new;

}

unsigned long
sdbm(unsigned char *str)
{
unsigned long hash = 0;
int c;

while ((c = *str++)!=0)
hash = c + (hash << 6) + (hash << 16) - hash;

return hash%26;
}

最佳答案

这里您使用的头文件cs50.h不是标准的c头文件。您可能知道该头文件中有一行#define unsigned char* string 即这里的 string 不是 c++ string 它意味着 char*.so 每当你使用 string 它将被解释为 char*。在 create 函数的代码中存在错误

 node* create(string val)
{
node* new = malloc(sizeof(node));
if(new!=NULL)
{
new->s=""; //ERROR Here

strcpy(new->s,val); // this is the part ehere I get Segmentation Fault
new->next=NULL;
}
return new;
}

您已经为node类型的new分配了空间,但尚未为new->s分配空间,它是一个指向 char 的指针,因此当您复制字符串时,它会出现段错误。

你的代码应该是这样的:

 node* create(string val)
{
node* new = malloc(sizeof(node));

if(new!=NULL)
{
new->s=malloc(strlen(val+1)*sizeof(char)); //add this line here
strcpy(new->s,val);
new->next=NULL;
}
return new;
}

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

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