# Using recursion and dynamic memory allocation of multidimensional arrays to find the determinant of an NxN matrix

I'm trying to write a program that can calculate the determinant of any NxN matrix regardless of the size but there's something wrong with the program and it crashes for any matrix with size greater than 1.

I'd be very grateful to anyone who can tell me what I'm doing wrong. I'm new to c++ and dynamic memory so, take it easy on me please (:.

Here's my program:

``````#include <iostream>

using namespace std;

int determinant(int *matrix[], int size);
void ijMinor(int *matrix[], int *minorMatrix[], int size, int row, int column);

int main()
{
int size;
cout << "What is the size of the matrix for which you want to find the determinant?:\t";
cin >> size;

int **matrix;
matrix = new int*[size];
for (int i = 0 ; i < size ; i++)
matrix[i] = new int[size];

cout << "\nEnter the values of the matrix seperated by spaces:\n\n";
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
cin >> matrix[i][j];

cout << "\nThe determinant of the matrix is:\t" << determinant(matrix, size) << endl;

return 0;
}

int determinant(int *matrix[], int size){
if(size==1)return matrix[0][0];
else{
int result=0, sign=-1;
for(int j = 0; j < size; j++){

int **minorMatrix;
minorMatrix = new int*[size-1];
for (int k = 0 ; k < size-1 ; k++)
matrix[k] = new int[size-1];

ijMinor(matrix, minorMatrix, size, 0, j);

sign*=-1;
result+=sign*matrix[0][j]*determinant(minorMatrix, size-1);
for(int i = 0; i < size-1; i++){
delete minorMatrix[i];
}
}

return result;
}
}

void ijMinor(int *matrix[], int *minorMatrix[], int size, int row, int column){
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(i < row){
if(j < column)minorMatrix[i][j] = matrix[i][j];
else if(j == column)continue;
else minorMatrix[i][j-1] = matrix[i][j];
}
else if(i == row)continue;
else{
if(j < column)minorMatrix[i-1][j] = matrix[i][j];
else if(j == column)continue;
else minorMatrix[i-1][j-1] = matrix[i][j];
}
}
}
}
```
```

Your `minorMatrix` consists of uninitialised pointers because of this:

``````minorMatrix = new int*[size-1];
for (int k = 0 ; k < size-1 ; k++)
matrix[k] = new int[size-1];
```
```

`matrix[k]`should be `minorMatrix[k]`.