我正在开发一个程序,该程序将显示一个数组的所有可能排列,然后将唯一排列存储在另一个数组中,但是我在存储唯一排列时遇到了问题。我正在检查我的代码并遇到了一些错误,因为我创建了 uniquePermutations 变量并且没有初始化。在尝试访问该变量后,程序会崩溃,所以我尝试将其设置为等于 nullptr 这有帮助。
现在,当我使用我的copyUniquePermutations 函数(在permute 函数中调用时,它会使用nullptr检查数组是否为空strong> 然后如果是,我们声明 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;
}
最佳答案
我认为这里你需要在 newArray[j]
中包含 j
for (int j = 0; j<3; j++)
newArray[i] == NULL;
关于c++ - 排列程序无法写入数组 - 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614427/