簡體   English   中英

發生此錯誤:在0x0F2BFB7C(ucrtbased.dll)引發異常正在嘗試更改大小嗎?

[英]This Error Occurs: Exception thrown at 0x0F2BFB7C (ucrtbased.dll) Is trying to change the size the problem?

因此,我正在制作一個選擇排序程序,在該程序中,我必須輸入兩個值:一個用於數組中使用的數字,另一個用於隨機數生成器的種子。 我對如何調整使用的數字有些困惑,因為我們可以放入的最大元素數是15。數組當前有8。每個元素應該是20到40之間的數字。

#include <iostream>
using namespace std;

int selectionSort(int[], int);

int selectionSort(int numbers[], int numbersSize) {
    int i = 0;
    int j = 0;
    int indexSmallest = 0;
    int temp = 0;  // Temporary variable for swap

    for (i = 0; i < numbersSize - 1; ++i) {

        // Find index of smallest remaining element
        indexSmallest = i;
        for (j = i + 1; j < numbersSize; ++j) {

            if (numbers[j] < numbers[indexSmallest]) {
                indexSmallest = j;
            }
        }

        // Swap numbers[i] and numbers[indexSmallest]
        temp = numbers[i];
        numbers[i] = numbers[indexSmallest];
        numbers[indexSmallest] = temp;
    }
    return indexSmallest;
}

int main() {
    int numbers[] = {10, 2, 78, 4, 45, 32, 7, 11};
    const int NUMBERS_SIZE = 15;
    int i = 0;
    int nums = 0;
    int seed = 0;

    cin >> nums;
    cin >> seed;

    srand(seed);

    for (int i = 0; i < nums; i++) {
        numbers[i] = (rand() % 20) + 20;
    }

    cout << "UNSORTED: ";
    for (i = 0; i < NUMBERS_SIZE; ++i) {
        cout << numbers[i] << " ";
    }
    cout << endl;

    selectionSort(numbers, NUMBERS_SIZE);

    cout << "SORTED: ";
    for (i = 0; i < NUMBERS_SIZE; ++i) {
        cout << numbers[i] << " ";
    }
    cout << endl;
}

當我輸入“ 10 100”(10是要在數組中使用的數字,而100是種子)時,我會在輸出屏幕中看到:

未分類:25 36 35 24 24 34 38 22 29 29 5634432 10498254 1 8896376 8876856

排序:1 22 24 24 25 29 29 34 35 36 38 5504116 5785352 5787344 15085774

代碼中的錯誤:Project11.exe中的0x0F45FBA0(ucrtbased.dll)引發異常:0xC0000005:訪問沖突讀取位置0x00BF9640。

我敢打賭這與數組的大小有關,因為原始大小只有8,但我們使用的是數組中的10個數字,因此后兩個為空。 如何更改數組輸入,以便正確輸入每個值?

您在numbers的末尾寫入,導致未定義行為(在這種情況下,將覆蓋堆棧並可能更改返回地址)。

由於cout語句中有錯字,因此您的SORTED輸出是垃圾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM