繁体   English   中英

CS50 pset5加载功能

[英]CS50 pset5 Load Function

我在CS50上的pset5的加载部分遇到了一些麻烦,如果有人可以提供帮助,那就太好了。 我正在尝试加载从字典(下面的文件fp)中读取的特里,然后遍历字母以创建特里。

我了解构建特里的概念,但是我认为我在结构指针的设置方面缺少一些东西(希望我不会在下面的代码中走得很远)。 我尝试设置“陷阱”以浏览尝试的每个阶段。

我目前遇到细分错误,因此无法完全确定下一步该怎么做。 任何帮助将不胜感激。

/** 
* Loads dictionary into memory.  Returns true if successful else false.
*/
bool load(const char* dictionary)
{
    //create word node and set root

    typedef struct node {
        bool is_word;
        struct node* children[27];
    } node;

    node* root = calloc(1, sizeof(root));
    root -> is_word = false;
    node* trav = root;

    //open small dictionary

    FILE* fp = fopen(dictionary, "r");
    if (fp == NULL)
    {
        printf("Could not open %s.\n", dictionary);
        return false;
    } 

    //read characters one by one and write them to the trie

        for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
        {

            //set index using to lower.  Use a-1 to set ' to 0 and other letters 1-27

            int index = tolower(c)-('a'-1);

            //if new line (so end of word) set is_word to true and return trav to root)

            if (index == '\n')
            {
                trav->is_word = true;
                trav = root;
            }

            //if trav-> children is NULL then create a new node assign to next
            //and move trav to that position

            if (trav->children[index] == NULL)
            {
                node* next = calloc(1, sizeof(node));
                trav->children[index] = next;
                trav = next;
            }

            //else pointer must exist so move trav straight on

            else {
                trav = trav->children[index];
            }

    }

    fclose(fp);

    return false;
}

我假设您将数组children[]的大小设置为存储26个字母和撇号。 如果是这样,则当fgetc(fp)返回带有acsii代码39的撇号(我认为)时, index将设置为-57,这绝对不是trav->children一部分。 那可能就是您遇到段错误(或至少其中一个地方)的地方。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM