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

dynamic 2d array access violation with remainders

我在尝试使用此代码实现组快速 select 算法时遇到了这个非常奇怪的问题。我使用一个 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];
}