gpt4 book ai didi

c++ - 带余数的动态二维数组访问冲突

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:50 25 4
gpt4 key购买 nike

在尝试使用此代码实现组快速选择算法时,我遇到了这个非常奇怪的问题。我使用一个 2D 动态分配数组来保存随机生成的 10 个数字的未排序数组中的各个元素。当我以 2、5 或 10 的组大小运行代码时,它运行良好。但是,当我将组大小更改为一个数字,使一个组比其他组小时,当我尝试将数组的内容初始化为一些测试数字时,它会中断。感谢您的任何建议。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include <array>

using namespace std;

int groupSize = 0;
int groupSelect(int *, int, int, int);

int main()
{

// randomize array of size 10 with entries between 1 and 20.

random_device rd;
mt19937 eng(rd());
uniform_int_distribution<> distr(1, 20);

int max = 10;

int * Array;
Array = new int[max];

for (int i = 0; i < max; i++)
{
Array[i] = distr(eng);
}

// display array contents (unsorted)

cout << "Array contents are:\n";
for (int i = 0; i < max; i++)
{
cout << Array[i] << ", ";
}

cout << endl;

/*------------------------------------------------------------------------------*/

groupSize = 3;

int poo = groupSelect(Array, 0, 9, 5);

return 0;

/*------------------------------------------------------------------------------*/


delete[] Array;
}


int groupSelect(int* arr, int start, int end, int k)
{
bool remainder = false;
int size = 10;

if ((size % groupSize) != 0)
{
remainder = true;

}

//size = amount of groups of 5 (and remainder group)
size = size - (size % groupSize);
size = size / groupSize;

if(remainder)
size++;


cout << "Size = " << size << endl;

int** groups = new int*[size];
for (int i = 0; i < size; ++i)
{
if (remainder == true)
{
if (size - i == 1)
groups[i] = new int[((size) % (groupSize))];
}
else
groups[i] = new int[groupSize];
}


int testV = 0;
for (int i = 0; i < size; i++)
{

int temp = groupSize;
if (size - i == 1)
{
if (remainder)
temp = size % groupSize;
}
for (int j = 0; j < temp; j++)
{
groups[i][j] = testV; // codes break here
testV++;
}
}

cout << "\nGroup arrays' contents\n" << endl;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < groupSize; j++)
{
cout << "groups[" << i << "]["<<j<<"] contents = " << groups[i][j] << endl;
}
}

delete[] groups;

return 0;
}

最佳答案

你在这篇文章中有一个错误:如果 remainder 为真但 size - 1 != 1 你永远不会初始化你的数组然后你试图访问它们

for (int i = 0; i < size; ++i)
{
if (remainder == true)
{
if (size - i == 1)
groups[i] = new int[((size) % (groupSize))];
}
else
groups[i] = new int[groupSize];
}

关于c++ - 带余数的动态二维数组访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895604/

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