【问题标题】:C: Linked list hash table population issueC:链表哈希表填充问题
【发布时间】: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 的单词部分),但事实并非如此

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

【问题讨论】:

  • 嗯......你不能分配给一个数组类型。您可能想要memcpystrcpy(或它们的安全变体)。
  • 我之前尝试过类似的方法,但遇到了分段错误,所以我以为我走错了路
  • table[hashed_word]->wordNULL->word 因为table[hashed_word] == NULL(还有node* table[500]; 没有初始化)

标签: c list dictionary hashtable


【解决方案1】:

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

当您尝试添加单词时,您尝试将其写入表中已经存在的节点中,而不是仅仅将新分配的节点链接到表中。

你的表也是一个局部变量,所以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;
}

【讨论】:

  • 非常感谢。您能否解释一下最后两行(new_node->next = table[hashed_word]; 和 table[hashed_word] = new_node;)。在我看来,new_node->next 指针指向索引 hashed_word 处的表,然后将 new_node 分配给索引 hashed_word 处的表。那不就是new_node的in指针指向new_node吗?
  • @user1636588:这两行将新节点放在表中该索引的列表前面。所以表指向新节点,新节点指向表中以前列表的头部。当表为空时(开始时),它将为 NULL。
猜你喜欢
  • 2020-09-03
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多