2016-02-12 36 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

我沒有意識到,我得到用戶輸入之前初始化數組,謝謝。 –