#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 Community 2013 中运行此代码,如果我输入一个较大的数字(如 10),则会出现堆损坏错误。从我所读到的内容来看,当您尝试写入未分配的内存地址时,会发生堆损坏错误,但我不明白两件事:
1)为什么动态数组会发生这种情况,以及2)为什么只有当我尝试输入更大的数字时才会发生错误。
-
卢克您已经定义了数组的大小。所以它不是一个动态数组。它是指向大小为 5 的数组的指针,因此最多只能存储 5 个整数。
-
所以你基本上已经分配了足够的空间来容纳 5 int。这意味着,如果您尝试存储超过 5 个,例如索引为 5 的第 6 个 int,则您正在尝试访问不属于您的内存。例如,这里有:
[] []
1 2 3 4 5
很好
[] [] [][] []
1 2 3 4 5 6 7 8 ...
导致堆损坏。
我可以建议标准::矢量吗?