I am currently trying to inverse a dynamic square (n by n) matrix. The code works for a 2*2 matrix if i specify the elements. However when i tried to make the code work for a dynamic matrix which prompts the user to enter the elements, it crashes. I do not know how dgetri_really works so its proving difficult to solve this problem. Help please!!! Here is my code so far.
#include<stdio.h>
#include<stdlib.h>
void dgetri_ ( int* n, double** A, int* lda,int* ipiv, double* work, int* lwork, int* info );
void dgetrf_ ( int* m, int* n, double** a, int* lda,int* ipiv, int* info );
// this allocates memory to the dynamic matrix//
double** allomat (int row, int col)
{
double **matrix;
int i;
matrix = (double **) malloc (row*sizeof(double *));
if (!matrix) return NULL;
matrix[0] = (double *) malloc (row*col*sizeof(double));
if (!matrix[0])
{
free(matrix);
return NULL;
}
for (i = 1; i < row; i++)
matrix[i] = matrix[i-1] + col;
return matrix;
}
// this part of the code carries out matrix inversion//
void inverse (double** A, int n) {
int i,n,j;
int lda;
int *ipiv;
int lwork;
int info;
double* work;
lda=n;
ipiv = (int*)malloc(20*n*sizeof(int));
work = (double*)malloc(100*n*(sizeof(double)));
dgetrf_ ( &n, &n, A, &lda, ipiv, &info );
printf ("Matrix A after dgetrf\n");
for (i=0;i<n;i++) {
for (j=0;j<n;j++)
{
printf ("A[%d][%d]:%f\t", i,j,A[i][j]);
}
}
printf ("\ninfo for dgetrf_:%d\n\n", info);
lda=n;
lwork=100*n; //magic number - dimension of work
dgetri_ (&n, A, &lda, ipiv, work, &lwork, &info);
printf ("Matrix A after dgetri\n");
for (i=0;i<n;i++) {
for (j=0;j<n;j++){
printf ("A[%d][%d]:%f\t", i,j,A[i][j]);
}
}
printf ("\ninfo for dgetri_:%d\n\n", info);
free (ipiv);
free (work);
}
int main ()
{
int i,j,n;
double **A;
double **Ainv;
printf
scanf("%d",&n);
A = allomat(n,n);
Ainv = allomat(n,n);
if (!A||!Ainv)
{printf("error in malloc\n");}
for (i=0;i < n; i++){
for(j=0;j<n;j++)
{ scanf("%lf",&A[i][j]);
}
}
for (i=0;i < 2; i++){
for(j=0;j<2;j++)
{ Ainv[i][j]=A[i][j];
}
}
printf("crap\n");
for (i=0;i < 2; i++){
for(j=0;j<2;j++)
{ printf("%lf\n", Ainv[i][j]);
}
}
inverse(A,2);
free (A);
free(Ainv);
return 0;
}

