【问题标题】:CS50 pset5 SpellerCS50 pset5 拼写器
【发布时间】:2020-05-22 11:46:30
【问题描述】:

这是我在这里的第一篇文章,我需要帮助。 拼写器对 lalaland.txt 的输出是 958 个单词,但应该是 955。(3 x "i'd")。 我曾尝试硬编码“i'd”,但输出约为 850。 (程序拒绝了所有的“我会”)。 tolstoy.txt - 13117,但必须是 13008,大多数单词是两个字母(Ha、ha、ga、Ma、I'd 等)。 同时同一单词的其他部分通过检查。 所有其他文本的情况相同。程序无缘无故地通过和拒绝相同的单词。 我不知道发生了什么。

这是我的负载();

bool load(const char *dictionary)
{
    FILE *inputFile = fopen(dictionary, "r");
    if (inputFile == NULL)
    {
        return false;
    }

    while (true)
    {
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            return 1;
        }
        n->next = NULL;
        int sc = fscanf(inputFile, "%s", n->word);
        if (sc == EOF)
        {
            free(n);
            break;
        }

        int bucket = hash(n->word);
        if (table[bucket] == NULL)
        {
            table[bucket] = n;
        }
        else
        {
            n->next = table[bucket]->next;
            table[bucket]->next = n;
        }
        sizeCount++;
    }
    fclose(inputFile);
    return true;
}

和检查();

bool check(const char *word)
{
    int i = hash(word);
    if (table[i] == NULL)
    {
        return false;
    }
    struct node *checker = malloc(sizeof(node));
    checker = table[i];
    while (true)
    {
        if (strcasecmp(checker->word, word) == 0)
        {
            return true;
        }
        if (checker->next == NULL)
        {
            break;
        }
        checker = checker->next;
    }
    free(checker);
    return false;
}

【问题讨论】:

  • 看起来像是复制/粘贴事故;实际检查功能未发布。
  • 第一次发帖失败))。谢谢。

标签: cs50


【解决方案1】:

请记住,table 是节点指针数组,而不是节点数组。因此,没有为nextword 元素分配内存。 load 中的这些行正在访问不属于 table[bucket] 的内存:

n->next = table[bucket]->next;
table[bucket]->next = n;

由于table 是链表的头部,所以不需要在检查中分配一个节点。如果checker 是一个节点指针,初始化为table[bucket],程序将很好地抓取列表,并且(应该)只访问分配的内存。

内存违规导致不可预知的结果。您可以运行valgrind -v 来查看完整报告。

【讨论】:

  • 非常感谢!你的回答很有帮助。现在我看到了节点和指向节点的指针之间的区别。这很简单,但我没有注意到。我还为检查、加载和卸载功能做了一个指针。谢谢队友!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2020-10-04
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多