2016-05-12 53 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