2016-02-23 46 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