2016-02-12 34 views
0
#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)为什么错误只发生在我尝试输入更大数字时。

+2

为什么不在获取大小输入后分配数组? – DigitalNinja

+1

对于数字2,向[橡皮鸭](https://en.wikipedia.org/wiki/Rubber_duck_debugging)解释你的代码。 –

+1

对于编号1:这实际上与动态分配没有任何关系。你只是不能访问你不拥有的内存,并不重要*你违反了这条规则。 –

回答

1
  1. Luke, 您已经定义了数组的大小。所以它不是一个动态数组。它是一个指向数组的指针,它的大小为5,因此最多只能存储5个整数。

  2. 所以你基本上已经分配了足够的空间来容纳5个int。这意味着如果您尝试存储5个以上的索引,例如第5个索引处的第6个int,则您尝试访问不属于您的内存。 例如这里你有:

[] [] [] [] []

[] [] [] [ ] []

1 2 3 4 5 6 7 8 ...

原因堆损坏。

可能我建议std :: vector?

+0

我没有意识到,我得到用户输入之前初始化数组,谢谢。 –