2011-10-31 82 views
0

好,所以我定义我的结构是这样的。特里数据结构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; 
} 
+1

你必须在'child'指针分配内存。你知道'malloc' /'calloc'?或者你创建其他'trie's并把它们放在你能告诉我们你的代码? – birryree

+2

这是C或C++?这些问题的答案会疯狂地不同。 –

+3

其中,是代码填充你的trie? –

回答

1
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; 

你也必须改变根的malloc:

struct trie *root = newtrie(0); 

哪个更清楚,并且避免了我提到的错误。 http://codepad.org/J6oFQJMb 6次左右的呼叫后没有段错误。

我也注意到你的代码malloc是一个新的root,但从来没有返回它,所以除了这个函数之外,没有人能看到它。这也是一个内存泄漏。

+0

我该如何解决这个问题? – Relics

+0

当我定义结构时,我应该为孩子使用malloc吗? – Relics

+0

ug我感谢你的帮助,也许即时只是实施错误,但我仍然得到seg错误 – Relics

1

除了@ MooingDuck的答案,这里还有另外一个问题,您的代码:

int addWordOccurrence(const char* word) 
{ 

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

你做的

root = (struct trie *)malloc(sizeof(struct trie*)); 

,但你真的要分配'的sizeof(结构线索) ,而不是指针的大小(如果你在x86或x86_64上,这可能是4或8)。

这是更好的(不需要用C malloc的返回指针的显式转换,你可以做sizeof这样的:

struct tree *root = malloc(sizeof(*root));