【发布时间】:2016-12-01 23:13:27
【问题描述】:
我是 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 的单词部分),但事实并非如此
有人能告诉我我做错了什么吗?我想这是非常基本的,因为指针令人困惑!我已经坚持了好几天了,开始有点沮丧,所以很想得到任何可以提供的帮助。
【问题讨论】:
-
嗯......你不能分配给一个数组类型。您可能想要
memcpy或strcpy(或它们的安全变体)。 -
我之前尝试过类似的方法,但遇到了分段错误,所以我以为我走错了路
-
table[hashed_word]->word是NULL->word因为table[hashed_word] == NULL(还有node* table[500];没有初始化)
标签: c list dictionary hashtable