2016-02-23 43 views
-2

嗨,我想创建一个使用动态数组的冒泡排序,代码似乎工作,但会引发运行时错误: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; 
    } 
} 
+0

“*因为我试图学习动态数组我自己*” - 您的错误与动态数组无关。您正在运行数组的边界。 – PaulMcKenzie

回答

1

作为评价上述(它是),则正在阅读的阵列外部。

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

for循环的最后一次迭代,你会覆盖一切是阵列结束后。数组a[length]仅在0length - 1之间有效。

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

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

+0

谢谢@James Root我没有注意到交换数组的长度。我修好了,它工作正常。另外我已经解决了排序所有数字的问题。但是,你可以''解释'为什么我得到了运行时错误''说明堆损坏? – dbn