嗨,我想创建一个使用动态数组的冒泡排序,代码似乎工作,但会引发运行时错误:HEAP腐败检测(因为我删除动态数组...我不明白为什么我得到这样的错误)。此外,给定数组中的最后两个元素得到排序,但我得到的最后一个元素显示的地址。正如我试图学习动态数组一样,亲切地帮助我理解错误。提前致谢 !!!使用动态数组进行冒泡排序时发生堆损坏错误
阵列= {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;
}
}
“*因为我试图学习动态数组我自己*” - 您的错误与动态数组无关。您正在运行数组的边界。 – PaulMcKenzie