排列程序无法写入数组 - 运行时错误

时间:2018-02-05 00:34:51

标签: c++ arrays algorithm pointers

我正在开发一个程序,它将显示数组的所有可能的排列,然后将唯一的排列存储在另一个数组中,但是我遇到了存储唯一排列的问题。我正在浏览我的代码,因为我创建了 uniquePermutations 变量并且没有初始化,因此出现了一些错误。在尝试访问该变量后,程序会崩溃,然后我尝试将其设置为 nullptr ,这有助于。

现在,当我使用 copyUniquePermutations 函数(在 permute 函数中调用时,它会检查数组是否为空, nullptr 然后如果是,我们声明3个新数组,并设置每个点等于 NULL ,这样我们就不会得到任何未定义的行为。接下来,我检查是否有任何点是 NULL 这样我们就不会进入可能导致问题的 equalArrays 函数,然后我们会进入导致问题的赋值部分。因为我们分配了 newArray [ i] NULL 为什么计算机会说它写入这个位置有问题?

#include <iostream>
using namespace std;

int permutations[] = { 2, 1, 2 };

void swap(int &x, int &y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}

bool equalArrays(int array1[], int array2[], int size)
{
    for (int i = 0; i < size; i++)
        if (array1[i] != array2[i]) return false;

    return true;
}

void copyUniquePermutations(int oldArray[], int *newArray[])//This is the function that is causing issues
{
    for (int i = 0; i < 3; i++)
    {
        if (newArray == nullptr)
        {
            newArray = new int*[3];
            for (int j = 0; j<3; j++)
                newArray[i] == NULL;
        }

        if (newArray[i] == NULL || !equalArrays(oldArray, newArray[i], 3))
        {
            for (int j = 0; j < 3; j++)
                newArray[i][j] == oldArray[j];
        }
    }
}


void permute(int permutations[], int *uniquePermutations[], int l, int r)
{
    int i;
    if (l == r)
        copyUniquePermutations(permutations, uniquePermutations);

    else
    {
        for (i = l; i <= r; i++)
        {
            swap((permutations[l]), (permutations[i]));
            permute(permutations, uniquePermutations, l + 1, r);
            swap((permutations[l]), (permutations[i]));
        }
    }
}


int main()
{
    int **uniquePermutations = nullptr;

    permute(permutations, uniquePermutations, 0, 2);

    for (int i = 0; i < 3 ; i++)
        delete[] uniquePermutations[i];

    delete[] uniquePermutations;


    return 0;
}

1 个答案:

答案 0 :(得分:1)

我认为您需要j

中有newArray[j]
 for (int j = 0; j<3; j++)
                newArray[i] == NULL;