嗨,我想創建一個使用動態數組的冒泡排序,代碼似乎工作,但會引發運行時錯誤: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