尝试编写堆化算法 - 分段错误
trying to write heapify algorithm - segmentation fault
我最终尝试使用堆排序来按字母顺序对已读入的单词进行排序。我以前从未做过堆,所以我试图跟着我的书。我正在使用 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 开始。
相关文章:
- 分段故障(堆芯转储)矢量
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 数组的指针从不分段故障
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 在线编译器中的分段C++没有打印消息
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段错误当我试图运行程序时出错
- 分段故障,合并排序算法
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 递归算法中的分段错误
- 尝试编写堆化算法 - 分段错误
- C++分段错误中的堆算法