c pointers recursion

# c - 行列式程序无法正常运行

1）determinant（）查找n * n矩阵的行列式

2）create（）动态分配一个* n数组

3）copy（）创建n * n数组的n-1 * n-1个未成年人

``````#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int determinant(int **a,int size,int noentry);// find determinant using recursion
int copy(int **b,int **a,int size,int noentry);//copy elements to minor
int **create(int size); // dynamically allocate a two dimensional array
int main()
{
int **a,size,i,j,y;
printf("enter the order of the determinant \n");
scanf("%d",&size);
a=create(size);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&a[i][j]);
}
}
y=determinant(a,size,0);
printf("the determinant is %d \n",y);
return 0;
}
int  determinant(int **a,int size,int noentry)
{
int i;
static int det=0;
if(size<=2)
return a[0][0]*a[1][1]-a[0][1]*a[1][0];
else
{
for(i=0;i<size;i++)
{

int **b;
b=create(size-1);
copy(b,a,size-1,i);
det= det+pow(-1,i)*a[0][i]*determinant(b,size-1,i);
}
return det;
}
}
int copy(int **b,int **a,int size,int noentry)
{
int i,j,k;
for(i=1;i<=size;i++)
{
k=0;
for(j=0;j<=size;j++)
{
if(j==noentry)
continue;
else
{
b[i-1][k]=a[i][j];
k++;
}
}
}
return size;
}
int **create(int size)
{
int **b;
if(size<=0)
{
printf("the size cannot be negative/null \n");
return NULL;
}
int i;
printf("entered the create function \n");
b=(int **)malloc(sizeof(int *)*size);
for(i=0;i<size;i++)
b[i]=(int *)malloc(size*sizeof(int));
return b;
}
``````

kapil

40
Serge Ballesta 2015-12-04 21:33

TL / DR：只需删除函数中变量`static`限定符即可`det``determinant`

``````int **create(int size)
{
int i;
int **b;
if(size<=0)
{
printf("the size cannot be negative/null \n");
return NULL;
}
printf("entered the create function \n");
b=(int **)malloc(sizeof(int *)*size);
b[0]=(int *)malloc(size * size*sizeof(int));
for(i=1;i<size;i++)
b[i]=b[0] + i * size;
return b;
}
void destroy(int **a) {
free(a[0]);
free(a);
}
``````

``````int  determinant(int **a,int size)
{
int i;
int det=0;
int m1 = 1;
if(size<=2)
return a[0][0]*a[1][1]-a[0][1]*a[1][0];
else
{
for(i=0;i<size;i++)
{

int **b;
b=create(size-1);
copy(b,a,size-1,i);
det= det+m1*a[0][i]*determinant(b,size-1);
destroy(b);
m1 = - m1;
}
return det;
}
}
``````