嗨,我正在尝试使用动态数组创建气泡排序,代码似乎有效,但抛出运行时错误:检测到堆损坏(因为我正在删除动态数组...我不明白为什么我会收到这样的错误)。此外,给定数组中的最后两个元素被排序,但我得到了最后一个元素显示的地址。因为我正在尝试自己学习动态数组。请帮助我了解错误。提前致谢!!
数组 = {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]
仅在 0
到 length - 1
范围内有效。
此外,您的气泡排序只运行一次,而它应该不断运行,直到所有项目都排序完毕。
在主观上,*(a+i)
与a[i]
相同,但可读性较差。