Below is a function I wrote used to evaluate the determinant of a nxn matrix. arguments are an array of the matrix values in order going from left to right jumping to the next line then going from left to right again.
An error happens after the function recursively calls itself once and attempts to allocate dynamic memory for a sub-matrix.
I'm not sure why this happens? Can anyone explain why an error occurs and how to correct it? Thanks.
[code=cpp]
double evaluate(double *mat,int dim)
{
//smallest case
if(dim==2)
{
return mat[0]*mat[3]+mat[2]*mat[1];
}
//smallest case
int b;
double result = 0;
//iterate through columns
for(int j =0; j<dim; j++)
{
//calculate b
if((j+2)%2==0)
{
b=1;
}
else
{
b=-1;
}
//calculate b
//smaller matrix
double *smaller = new double [(dim-1)*(dim-1)];//error occurs here after one recursive call
int counter=0;
for (int p = 0; p<dim*dim; p++)
{
if(dim != j)
{
smaller[counter]=mat[p];
counter++;
}
}
//smaller matrix
result+=b*mat[j]*evaluate(small er, dim-1); //recursive call
delete [] smaller;
}
return result;
}
[/code]
An error happens after the function recursively calls itself once and attempts to allocate dynamic memory for a sub-matrix.
I'm not sure why this happens? Can anyone explain why an error occurs and how to correct it? Thanks.
[code=cpp]
double evaluate(double *mat,int dim)
{
//smallest case
if(dim==2)
{
return mat[0]*mat[3]+mat[2]*mat[1];
}
//smallest case
int b;
double result = 0;
//iterate through columns
for(int j =0; j<dim; j++)
{
//calculate b
if((j+2)%2==0)
{
b=1;
}
else
{
b=-1;
}
//calculate b
//smaller matrix
double *smaller = new double [(dim-1)*(dim-1)];//error occurs here after one recursive call
int counter=0;
for (int p = 0; p<dim*dim; p++)
{
if(dim != j)
{
smaller[counter]=mat[p];
counter++;
}
}
//smaller matrix
result+=b*mat[j]*evaluate(small er, dim-1); //recursive call
delete [] smaller;
}
return result;
}
[/code]
Comment