尝试编写堆化算法 - 分段错误

trying to write heapify algorithm - segmentation fault

本文关键字:算法 分段 错误      更新时间:2023-10-16

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

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] < wordArray[c])部分。wordArray 的元素是刺痛,比较器从外部测试中正常工作。这与数组是动态的还是其他什么有关?我很困惑我在这里做错了什么。

你正在越界阅读。当您检查时:

if((c < size)

其中c是最后一个元素,您在此处读取越界:

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

检查应为:

if((c+1 < size)


另一个问题在这里:

while(r <= size)

其中r在代码中使用,如果它r == size,则明显超出界限。

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

您可以通过它的

n-1 行arr[n-1];//this is the nth element来访问数组的第 n 个元素

代码中出现分段错误

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

让我们假设size = 6

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