C:链表散列table人口问题

C: Linked list hash table population issue

我是 C 的新手,目前正在编写拼写检查程序。为此,我首先将单词字典加载到散列 table 中以便于引用。这是我的代码:

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)。然后我检查 table 在散列函数给出的索引处没有一个词。

然后我想开始一个 linked 列表,第一个 link 是第一个单词 ('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.

我认为这一行会将 table 的 'word' 部分指定为 'cat'(new_node 的单词部分),但它不会

有人能告诉我我做错了什么吗?我想这是非常基本的,因为指针令人困惑!我已经坚持了好几天,开始有点沮丧,所以希望能提供任何帮助。

您正在创建一个包含 500 个指针的 table,但您没有将其初始化为任何东西。然后你去检查元素以查看它们是否为空,它们可能是也可能不是(它们只是垃圾)。

当你尝试添加一个单词时,你尝试将它写入一个已经在 table 中的节点,而不是仅仅将新分配的节点链接到 table.

您的 table 也是局部变量,因此在 load 函数 returns 之后将无法访问 returns。

解决上述所有问题的最简单方法是将 table 和 struct node 定义设为全局:

typedef struct node
{
    char word[LENGTH + 1];
    struct node* next;
} node;

node *table[500] = { 0 };

然后使用循环填充table;

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;
}