Help passing nxn array to 2d array.
So I am new at C, and I am having trouble passing an NxN array to my determinant function. Can someone have a look at my code and tell me where i went wrong. trying to pass nxn array to 2d pointer.
Code:
/*Hrach Beglaryan
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double Determinant(double **a,int n)
{
double **b= NULL;
double det = 0;
int i,j,k,p;
if (n < 1) { //doesnt make sense
} else if (n == 1) { //determinant is itself
det = a[0][0];
} else if (n == 2) {
det = a[0][0]*a[1][1]-a[1][0]*a[0][1];
} else {
det = 0;
for (k=0;k<n;k++) {
b = malloc((n-1)*sizeof(double *));
for (i=0;i<n-1;i++)
b[i] = malloc((n-1)*sizeof(double));
for (i=1;i<n;i++) {
p = 0;
for (j=0;j<n;j++) {
if (j == k)
continue;
b[i-1][p] = a[i][j];
p++;
}
}
det += pow(-1.0,1.0+k+1.0) * a[0][k] * Determinant(b,n-1);
for (i=0;i<n-1;i++)
free(b[i]);
free(b);
}
}
return(det);
}
void Transpose(double **a,int n)
{
int i,j;
int x,y;
double z; //temporary allocation
for (i=1;i<n;i++) {
for (j=0;j<i;j++) {
z = a[i][j];
a[i][j] = a[j][i];
a[j][i] = z;
}
}
for(x=0;x<n;x++)
for(y=0;y<n;y++)
printf("%d",a[x][y]);
}
int main()
{
int n=0;
int i=0,j=0;
double **c;
double a[n][n];
int x=0,y=0;
double determinant;
printf( "\n///////////////////////////////////////////////////////////\n");
printf( " FUN WITH LINEAR ALGEBRA\n");
printf("/////////////////////////////////////////////////////////////");
printf("\nPlease Enter the dimension of the square matrix");
scanf("%d",&n);
printf( "Please enter elements of the matrix");
{
for(x=0;x<n;++x)
for(y=0;y<n;++y)
{
printf("\nPlease enter the [%d][%d] element",x,y);
scanf("%d",&a[x][y]);
}
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(x=0;x<n;x++)
for(y=0;y<n;y++)
c[i][j]=a[x][y]; //I get a segmentation fault here. I understand that it only lets me put my first element [0][0].
determinant=Determinant(c,n);
printf("The Determinant of the matix is ", determinant);
Transpose(c,n);
}