2016-05-12 54 views
0

我有一棵有結構的樹。我需要找到其最大數量(給定)的最小值。在樹中找到某物品(C)

Item this_word (link h, int max){ 
     Item word; 
     if (h == NULL) 
      return 0; 
     if (h->item->acc == max){ 
      word = h->item; 
      this_word(h->l, max); 
     } 
     else{ 
      this_word(h->l, max); 
      this_word(h->r, max); 
     } 
     return word; 
    } 

但我得到一個分段錯誤..

+0

鏈接變量是一個指針嗎?因爲你像訪問它一樣 – BackDoorNoBaby

+0

你的段錯誤究竟在哪裏?你在調試器中運行程序嗎?請顯示'Item'和'link'類型的定義。 – Martin

+1

@BackDoorNoBaby typedefs是邪惡的 –

回答

0

您的代碼段錯誤時h!= NULLh->item->acc == max成立。在這種情況下,else分支被執行並返回單詞,這是之前沒有設置的。你可以通過正確地賦值給單詞來解決這個問題。

Item this_word (link h, int max){ 
     Item word; 
     if (h == NULL) { 
      return 0; 
     } 
     if (h->item->acc == max) { 
      word = h->item; 
      this_word(h->l, max); 
     } else { 
      // assign a certain value to word 
      this_word(h->l, max); 
      this_word(h->r, max); 
     } 
     return word; 
    } 

至於我可以看到你的代碼是有點不可思議,這是這種情況,因爲一個人不能全面瞭解您要根據您的問題是什麼。爲了提高安塞爾的質量,提供一個更好的問題(添加代碼,解釋上下文等)

+0

我做到了並且我仍然遇到分段錯誤。該結構有一個字符串和一個數字。樹是通過字符串組織的,我想返回給定數字的結構體。當有兩個像「一」和「計算機」這個數字我想返回「計算機」,因爲它是按字母順序 – Heather

+1

@ Heather,所以樹被排序的字符串。你想獲得具有一定數量的「最小」字符串?你應該明確地添加這個到你的問題!樹是否被正確初始化?如果返回NULL,是否會導致段錯誤?我想我們需要更多的代碼.. – jboockmann

+0

我用'void init(){ head = NULL; }'初始化樹。何時返回NULL? – Heather