【问题标题】:trying to write heapify algorithm - segmentation fault尝试编写 heapify 算法 - 分段错误
【发布时间】:2015-01-20 03:05:27
【问题描述】:

我最终尝试使用 heapsort 按字母顺序对已读入的单词进行排序。我以前从未做过 heaps,所以我试图跟随我的书。我正在使用 cin 将单词存储到动态分配的数组中,因为单词的数量提前是未知的。从单独的代码中,我知道它正在被读入并且数组正在正确地变大。然后我试图堆化这个数组,但是由于我是编程新手,所以我一直遇到分段错误,我无法确定如何将其追溯到我做错的事情。这是我的 heapify 代码:

void Heap::make(){
    //make a heap from wordArray
    //r = last non-leaf
    for(int r = size/2; r > 1; r--){
        int c = 2 * r; //location of left child
        while(r <= size){ //size is a data member of Heap
//if r has 2 children and right is larger, make c the right child
            if((c < size) && (wordArray[c] < wordArray[c+1])){
                c++;
            }
//fix if parent failed heap-order condition
            if(wordArray[r] < wordArray[c]){

                swap(wordArray[r], wordArray[c]);
                r = c;    //check that it didn't get messed up at c
                c = 2 * c;
            }
            else{
                break; //heap-order condition holds so stop
            }
        }    
    }   
}

通过玩 couts,我可以确定该程序在 if(wordArray[r] &lt; wordArray[c]) 部分之前一直有效。 wordArray 的元素是stings,比较器在外部测试中正常工作。这与动态数组有关吗?我对我在这里做错了什么感到困惑。

【问题讨论】:

  • 你有没有试过调试代码找到问题的根源?
  • 不知道您的数据类型、数组最大值等。如果 r==size 则 c ==2*size 大于 size。然后 wordarray[c] 是未定义的。
  • 我的猜测是你读到了数组的末尾。第一次点击 wordArray[c],c=2*r = 2*size/2,所以你可能正在读取 wordArray[size],但由于它是零索引,这已经结束了。
  • 你们搞定了,我的索引与“位置”混淆了。我从这本书中混淆了,因为它从一棵二叉树中显示它的大小为 1,而数组索引必须从 0 到 size-1/我只需要从变量中取 -1 就可以了。谢谢!

标签: c++ arrays algorithm heap heapsort


【解决方案1】:

您正在阅读超出范围。检查时:

if((c < size)

其中c 是最后一个元素,您在此处读取超出范围:

 if((c < size) && (wordArray[c] < wordArray[c+1])){
                                             ^

检查应该是:

if((c+1 < size)


还有一个问题:

while(r <= size)

如果r == size 明显超出范围,则在代码中使用r

对于大小为n 的数组,它们的元素来自0 to n-1,因此访问n 个元素是未定义的行为。

【讨论】:

    【解决方案2】:

    您可以通过它的第 n-1 行访问数组的第 n 个元素arr[n-1];//this is the nth element

    代码中出现分段错误

    (wordArray[c] < wordArray[c+1]) // try to modify this.
    

    让我们假设size = 6

    Whwn for() 循环将首次运行,c = 2*6 表示 6,而您访问的 arr[6] and arr[6+1] 均无效。数组索引从零而不是一开始。

    【讨论】:

      猜你喜欢
      • 2013-05-09
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      相关资源
      最近更新 更多