c - 数据结构C

扫码查看

好的,所以我这样定义我的结构。

    struct trie {
        struct trie *child[26];
        int count;
        char letter;
    };


问题是当我尝试用单词填充我的特里时,出现了段错误。
有人告诉我,问题在于子变量没有指向任何东西,将它们设置为NULL将解决此问题。创建第二个结构也是实现此目的的好方法。我是C编程的新手,对如何创建第二种结构来实现此目的感到困惑。任何帮助将非常感激。

int addWordOccurrence(const char* word)
{

    struct trie *root;
    root = (struct trie *)malloc(sizeof(struct trie*));
    struct trie *initRoot=root;
    int count;

    int x=strlen(word);
    printf("%d",x);
    int i;
    for(i=0; i<x; i++)
    {
        int z=word[i]-97;
        if(word[i]=='\n')
        {
            z=word[i-1]-97;
            root->child[z]->count++;
            root=initRoot;
        }

        root->child[z] = (struct trie *)malloc(sizeof(struct trie));
        root->child[z]->letter=word[i];
        root->child[z]=root;
    }
    return 0;
}

最佳答案

root->child[z] = (struct trie *)malloc(sizeof(struct trie));
root->child[z]->letter=word[i];
root->child[z]=root;


这是有问题的。
1)如果已经设置child[z]怎么办?
2)您永远不会将child[z]->childchild[z]->count设置为任何值

#2导致您的段错误,#1是内存泄漏。

我的解决方案是编写一个用于分配新子代的函数:

struct trie* newtrie(char newchar) {
    struct trie* r = malloc(sizeof(struct trie));
    memset(r, 0, sizeof(struct trie));
    r->letter = newchar;
    return r;
}


然后您的代码将变为:

    if (root->child[z] == NULL)
        root->child[z] = newtrie(word[i]);
    root->child[z]=root;


您还必须更改root的malloc:

struct trie *root = newtrie(0);


这更清楚,并且避免了我提到的错误。 http://codepad.org/J6oFQJMb大约6次调用后无段错误。

我还注意到您的代码malloc是新的root,但是从不返回,因此除此函数外,没有人可以看到它。这也是内存泄漏。

关于c - 数据结构C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7959630/

10-12 17:42
查看更多