堆损坏 使用动态数组进行气泡排序时出错

Heap Corruption Error while doing bubble sort using dynamic arrays

本文关键字:气泡 排序 出错 数组 损坏 动态      更新时间:2023-10-16

嗨,我正在尝试使用动态数组创建气泡排序,代码似乎有效,但抛出运行时错误:检测到堆损坏(因为我正在删除动态数组...我不明白为什么我会收到这样的错误)。此外,给定数组中的最后两个元素被排序,但我得到了最后一个元素显示的地址。因为我正在尝试自己学习动态数组。请帮助我了解错误。提前致谢!!

数组 = {125,12,2,36,19}

#include "stdafx.h"
#include <iostream>
using namespace std;
 void bubblesort(int* a, int length); // for bubble sort//
int _tmain(int argc, _TCHAR* argv[])
{
int  size;
cout << " enter the size of array: " << endl;
cin >> size;
int* a = new int[size];
cout <<  "enter the elements in an array: " << endl;
for (int i = 0; i < size; i++)
cin >> *(a+i);
bubblesort(a, size);
delete[] a;
a = NULL;
return 0;
}
void bubblesort(int* a, int length)
{
int temp = 0;
for (int i = 0; i < length; i++)
{
    if (a[i] > a[i+1])
    {
        temp = a[i+1];
        a[i+1] = a[i];
        a[i]= temp;
    }
 }
for (int i = 0; i < length; i++)
    {
    cout << " The elements are : " << endl;
    cout << a[i] << endl;
     }
}

正如评论中提到的,您正在数组之外阅读。

a[i + 1] = a[i]; //When i == length - 1, this is UB

for 循环的最后一次迭代中,您将覆盖数组末尾之后的任何内容。数组a[length]仅在 0length - 1 范围内有效。

此外,您的气泡排序只运行一次,而它应该不断运行,直到所有项目都排序完毕。

在主观上,*(a+i)a[i]相同,但可读性较差。