C++ 堆排序错误:堆栈周围变量已损坏?
我正在为作业实现堆排序。我们必须像她在课堂上用伪代码那样做,否则我们就得不到学分 我收到一个运行时错误:变量“heapArray”周围的堆栈已损坏。我使用了调试器,但仍然无法找出导致错误的原因。我很确定这与HeapSort()函数中的For循环有关。有人能帮忙吗C++ 堆排序错误:堆栈周围变量已损坏?,c++,heap,heapsort,C++,Heap,Heapsort,我正在为作业实现堆排序。我们必须像她在课堂上用伪代码那样做,否则我们就得不到学分 我收到一个运行时错误:变量“heapArray”周围的堆栈已损坏。我使用了调试器,但仍然无法找出导致错误的原因。我很确定这与HeapSort()函数中的For循环有关。有人能帮忙吗 void HeapSort(int heapArray[]) { int heap_size = SIZE; int n = SIZE; int temp; Build_Max_Heap(heap
void HeapSort(int heapArray[])
{
int heap_size = SIZE;
int n = SIZE;
int temp;
Build_Max_Heap(heapArray);//function not implemented, only declared for compile
for(int i = n; i >=2; i--) //***I think error coming from something in here
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
heap_size = heap_size-1;
Max_Heapify(heapArray,1);//function not implemented, only declared for compile
}
return;
}
intmain()
{
int heapArray[SIZE]={5,99,32,4,1,12,15,8,13,55};
希普索特(希帕雷);
难道你写得太离谱了吗
for(int i = n; i >=2; i--)
{
temp = heapArray[1];
heapArray[1] = heapArray[i]; //THIS IS WRONG
heapArray[i] = temp; //
在c中,数组从0到n-1。heapArray用size声明
应该更像:
for(int i = n - 1; i >=2; i--) //Now you start from n-1
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
错误是:
for(int i = n; i >=2; i--)
您必须从n-1
开始,因为数组索引从0开始。正确的方法应该是
for(int i = n -1; i >=1; --i)
数组索引的越界错误,如果你从<代码> N>代码>开始,很可能你的书中的伪代码(使用方便)使用数组索引从1到<>代码> n>代码>,但是在C++中的实际程序中,我们应该从0开始到<代码> N-1 < /代码>。
for(int i = n -1; i >=1; --i)