使用 trie 的 Load 的 Pset5 实现

问题描述 投票:0回答:1

我在 pset5 上遇到了一些麻烦,我实际上不知道如何开始调试,我已经看了几次课程,但我没有任何进展..

当我运行 speller.c 时,它给我一个段错误,我运行了调试器,它在 For 循环开始时崩溃了,下面是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>

#include "dictionary.h"
// default dictionary
#define DICTIONARY "dictionaries/large"

//created the struct node
typedef struct node
{
    bool is_word;
    struct node * paths[27];
}
node;

int letter = 0;
char * word = NULL;

/**
 * Returns true if word is in dictionary else false.
 */ 
bool check(const char *word)
{
//todo
return false;
}

/**
 * Loads dictionary into memory. Returns true if successful else false.
 */
bool load(const char *dictionary)
{
//opens dictionary for reading
FILE *fp = fopen(DICTIONARY, "r");
if (fp == NULL)
{
    return false;
    unload();
}

//creates the root of the trie
node *root = malloc(sizeof(node));
root -> is_word = false;

node * trav = root;

char * word = NULL;

//start reading the file
while (fscanf(fp, "%s", word) != EOF)
{
    for (int i = 0; i < strlen(word); i++)
    {
        //assessing which path to take
        char c = fgetc(fp);
        if (isupper(c))
        {
            letter = tolower (c);
            letter = letter -'a';
        }
        else if (isalpha(c))
        {
            letter = c;
            letter = letter -'a';
        }
        else if (c == '\'')
        {
            letter = 26;
        }
        else if (c == '\0')
        {
            trav -> is_word = true;
        }
        if (trav -> paths[letter] == NULL)
        {
            node *new_node = malloc(sizeof(node));
            if (new_node == NULL)
            {
                return false;
               unload();
            }
            //point to new node
            trav -> paths[letter] = new_node;
        }
        else
        {
            trav = trav -> paths[letter];
        }
    }

}
if (fscanf(fp, "%s", word) == EOF)
{
    fclose(fp);
    return true;
}
return false;
}

/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
// TODO
return 0;
}

/**
* Unloads dictionary from memory. Returns true if successful else false.
 */
bool unload(void)
{
// TODO
return false;
}

我也不知道如何将 new_node 指向下一个新节点,以及是否必须为它们指定不同的名称。例如,我要存储单词“foo”,所以我读取名为trav的节点,转到路径[5](f字母),检查它是否已经打开,如果没有(如果它是NULL)我创建了一个名为 new_node 的节点并将 trav -> paths[5] 指向它,而不是我应该将 trav 更新为新节点,所以我将它指向它自己的路径[字母]?

c trie cs50
1个回答
-1
投票

word
是一个
NULL
指针。并且
fscanf
不会(不能真的)为该指针分配内存。那么当
fscanf
想要取消引用
word
来写它读取的字符时会发生什么?您不能取消引用
NULL
指针,它会导致未定义的行为。我建议您改为将 word 定义为数组。

注意:答案取自评论

© www.soinside.com 2019 - 2024. All rights reserved.