c - 数据结构C

标签 c data-structures

好吧,我这样定义我的结构。

    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/

相关文章:

java - 总和相等的子数组的最大数量

java - 如何检查哈希表中的键是否具有特定的哈希码?

c - 返回一个列表作为数据结构契约

python - 给定列表生成 Python 字典的最有效方法

c - fdim 首字母缩写词代表什么?

c - 来自 `strsep` 的字符串标记未打印(段错误)

c - 如何指示可以使用内联 ASM 参数*指向*的内存?

c - 执行 strstr() 函数时出错

c - long long常量使用的后缀是什么

java - 找到包含所有三角形的最小面积平行四边形