c - 用函数修改 C 结构的子结构(用于 trie 的应用)

标签 c function pointers struct trie

我现在正在尝试用 C 语言创建一个 trie,将字典加载到 trie 中,但我在修改结构时遇到了问题。

我现在有一个生成空白节点的函数,它似乎工作正常。 main 函数扫描字典文件,并调用一个“插入”函数,如下所示:

while (ftell(inptr) < endIndex)
{
    fscanf(inptr,"%[^\n]", word);
    printf("%s\n", word);

    //main insert function
    insert(word, root);


    //skips past this word
    fseek(inptr, 1, SEEK_CUR);
}

这会立即进行测试,在测试中我尝试确定 trie 的“A”值中的 bool 值。

printf("%i\n", (int)(root -> ptr[0] -> isEnd));

但这会产生一个错误,因为 root 的指针显然为空(成员访问类型为“struct node”的空指针)。

函数insert的实现如下。

bool insert(char *word, struct node *root)
{
    if (strcmp(word, "") == 0)
    {
        for (int i = 0, size = 27; i < size; i++)
        {
            root -> ptr[i] = NULL;
        }
        root -> isEnd = true;
        return false;
    }
    else
    {
        //gets the first letter of the word
        char firstLetter = word[0];

        //figures out which place in the array it goes
        int firstLetterInt;
        if (isalpha(firstLetter))
        {
            firstLetterInt = firstLetter - 'a';
        }
        else
        {
            firstLetterInt = 26;
        }

        //gets the rest of the word
        char *subbuff = calloc(45,1);;
        memcpy(subbuff, &word[1], strlen(word) - 1);
        subbuff[strlen(word)] = '\0';

        if(!(root -> ptr[firstLetterInt]))
        {
            root -> ptr[firstLetterInt] = blankNode();
        }

        insert(subbuff, root -> ptr[firstLetterInt]);
        free(subbuff);
        return true;
    }
}

我知道我应该使用指针之类的东西,但我已经试过了,但我似乎无法让它工作。我什至尝试将节点作为 struct node **root 传递,但似乎出现了同样的问题。另一个奇怪的是,在 while 循环中,它们似乎识别出插入,因为当插入“caterpillar”时,“c”、“a”和“t”并没有被创建为新节点。

最佳答案

如果你不初始化结构 node insert 不会用魔法为你做那件事,你的代码有问题(至少你发布的片段)您是否从未创建结构 node 的任何实例,所以 root 是并且将永远是 null
这是一个演示代码,向您展示如何在函数中分配结构字段

#include <stdio.h>
/***struct defenition***/
typedef struct demo_t
{
    int foo;
    int bar;
}demo_t;
/***Function to change values***/
void insert(demo_t *demo)
{
    demo->foo = 1;
    demo->bar = 2;
}
/***main***/
int main()
{
    //create instance of struct
    demo_t demo;
    demo.foo = 0;
    demo.bar = 0;
    //pass the reference
    insert(&demo);
    //verify
    printf("foo = %d    bar = %d\r\n", demo.foo, demo.bar);

    return 0;
}

关于c - 用函数修改 C 结构的子结构(用于 trie 的应用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53930197/

相关文章:

c++ - Printf 参数顺序被忽略

c - 无法链接linux内核模块:警告:“snd_device_new”未定义

c++ - C++中如何将函数作为参数传递?

C : Array of pointers giving segmentation fault

c - popen 是标准 C 函数吗?

c - 为什么直接比较字符串失败,但是使用 char* 成功

c - 将整个数组作为参数传递给函数

r - 如何覆盖包命名空间中不可见的函数?

c++ - 整数指针数组的大小

C 计算器,有很多函数 in 函数 in 函数