#include <iostream>
#include <algorithm>
bool wayToSort(int i, int j) { return i > j; }
bool wayToSortAlt(int i, int j) { return i < j; }
int main()
{
using namespace std;
int size = 5;
int *myArray = new int[size] { 0 };
int option = 0;
cout << "How many numbers do you want to enter?: ";
cin >> size;
cout << "How do you want to sort? ([1] Greatest [2] Lowest): ";
cin >> option;
cout << "----\n";
// Get number inputs
for (int count = 0; count < size; ++count)
{
cout << "Enter a number: ";
cin >> myArray[count];
}
cout << "----\nSorted:\n----\n";
// Sort for highest numbers
if (option == 1)
sort(myArray, myArray + size, wayToSort);
else
sort(myArray, myArray + size, wayToSortAlt);
// Print each number
for (int count = 0; count < size; ++count)
{
cout << myArray[count] << "\n";
}
delete[] myArray; // Clean up
myArray = nullptr; //
return 0;
}
我在Visual社區2013中運行此代碼,並且如果我輸入一個高數字(如10),則會出現堆損壞錯誤。從我讀過的內容來看,當您嘗試寫入未分配的內存地址時發生堆損壞錯誤,但我不明白兩件事:嘗試對數組進行排序時發生堆損壞
1)爲什麼會發生這種情況,動態數組和 2)爲什麼錯誤只發生在我嘗試輸入更大數字時。
爲什麼不在獲取大小輸入後分配數組? – DigitalNinja
對於數字2,向[橡皮鴨](https://en.wikipedia.org/wiki/Rubber_duck_debugging)解釋你的代碼。 –
對於編號1:這實際上與動態分配沒有任何關係。你只是不能訪問你不擁有的內存,並不重要*你違反了這條規則。 –