2011-10-31 87 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));