gpt4 book ai didi

c++ - 此错误发生在 : Exception thrown at 0x0F2BFB7C (ucrtbased. dll) 是试图更改大小的问题吗?

转载 作者:行者123 更新时间:2023-11-28 04:32:26 38 4
gpt4 key购买 nike

所以我正在制作一个选择排序程序,我必须在其中输入两个值:一个用于数组中使用的数字,另一个用于随机数生成器的种子。我对如何调整使用的数量有点困惑,因为我们可以放入的最大元素数量是 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 输出是垃圾。

关于c++ - 此错误发生在 : Exception thrown at 0x0F2BFB7C (ucrtbased. dll) 是试图更改大小的问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509587/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com