【问题标题】:Permutations Program Unable to Write to Array - Runtime Error排列程序无法写入数组 - 运行时错误
【发布时间】:2018-02-05 00:34:50
【问题描述】:

我正在开发一个程序,该程序将显示数组的所有可能排列,然后将唯一排列存储在另一个数组中,但是我在存储唯一排列时遇到了问题。我正在检查我的代码并且遇到了一些错误,因为我创建了 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;
}

【问题讨论】:

  • 你为什么不使用std::vector
  • 我需要将不同的排列存储为数组,我认为您无法将数组存储在向量中。
  • A std::vector 是一个数组。
  • @brand5i2g -- 当我声明使用std::array 时,它是为了阻止无法将数组存储在向量中的说法。 std::array 是可复制和可分配的,是哑纯数组的基本替代品。否则,std::set 仅存储唯一项目,这是用于您的目的的容器,因为没有代码可以确定项目是否重复。

标签: c++ arrays algorithm pointers


【解决方案1】:

我认为这里你需要在newArray[j] 中有j

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2018-08-01
    • 1970-01-01
    • 2020-12-16
    相关资源
    最近更新 更多