I'm working on a program that will display all possible permutations for an array, and then store the unique permutations in another array, however I am having issues with storing the unique permutations. I was going through my code and was getting a few errors because I had created the uniquePermutations variable and hadn't initialized. After trying to access the variable the program would crash so then I tried setting it equal to nullptr which helped.
So now when I use my copyUniquePermutations function (which is called in the permute function, it checks to see if the array is empty with nullptr and then if it is, we declare 3 new arrays, and set each spot equal to NULL so that we won't get any undefined behavior. Then next, I check to see if any spots are NULL so that we won't get to the equalArrays function which may cause issues and then we get to the assignment part which causes issues. Since we assigned newArray[i] to be NULL why does the computer say that it is having issues writing to this spot?
#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;
}