[英]C: Linked list hash table population issue
我是C语言的新手,目前正在编写拼写检查器。 为此,我首先将单词词典加载到哈希表中以方便引用。 这是我的代码:
bool load(const char* dictionary)
{
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
}
node;
node* table[500];
FILE *fp;
fp = fopen("dictionaries/small", "r");
if(fp == NULL)
{
return 0;
}
node* new_node = malloc(sizeof(node));
fscanf(fp, "%s", new_node->word);
int hashed_word = hash_function(new_node->word);
if(table[hashed_word] == NULL) //if the table has no value at the index
{
table[hashed_word]->word = new_node->word; //Issue here
}
return 0;
}
此代码非常简单地读取文件的第一行(单词),然后对其进行哈希处理(第一个单词“ cat”给出的哈希值为2)。 然后,我检查哈希表给出的索引表是否没有单词。
然后,我想以第一个链接为第一个单词(“ cat”)开始链接列表,然后从那里开始构建它。 但是,当我运行此代码时,我在这里遇到问题:
table[hashed_word]->word = new_node->word; //Issue here
并得到这个错误:
dictionary.c:66:34: error: array type 'char [46]' is not assignable
table[hashed_word]->word = new_node->word;
~~~~~~~~~~~~~~~~~~~~~~~~ ^
1 error generated.
我以为这行会将表的“单词”部分分配为“猫”(new_node的单词部分),但事实并非如此
有人可以告诉我我在做什么错吗? 我认为这是非常基本的,因为指针令人困惑! 我已经坚持了好几天,并且开始有点沮丧,所以很乐意提供任何帮助。
您正在创建一个包含500个指针的表,但没有将其初始化为任何内容。 然后,您去检查元素以查看它们是否为null(它们可能是也可能不是)(它们只是垃圾)。
当您尝试添加单词时,您尝试将其写入表中已有的节点中,而不仅仅是将新分配的节点链接到表中。
您的表也是一个局部变量,因此在load
函数返回后将无法访问。
上面所有方法最简单的解决方法是使表和struct node
定义变为全局:
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
} node;
node *table[500] = { 0 };
然后使用循环填充表格;
bool load(const char* dictionary)
{
char word[256];
FILE *fp = fopen("dictionaries/small", "r");
if(fp == NULL)
return false;
while (fscanf(fp, "%255s", word) == 1) {
if (strlen(word) > LENGTH)
continue; // ignore words that are too long
int hashed_word = hash_function(word);
node* new_node = malloc(sizeof(node));
strcpy(new_node->word, word);
new_node->next = table[hashed_word];
table[hashed_word] = new_node;
}
fclose(fp);
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.