#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:这实际上与动态分配没有任何关系。你只是不能访问你不拥有的内存,并不重要*你违反了这条规则。 –