好吧,我这样定义我的结构。
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]->child
或 child[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/