So... i can compile the following code but it aborts right when we try to put the values typed into the matrix.
Code:
#include <stdio.h>
#include <stdlib.h>
void allocheckm(float **m){
if(!m){
puts("Error in allocating!");
free(m);
exit(1);
}
}
void allocheckl(float *m){
if(!m){
puts("Error in allocating!");
free(m);
exit(1);
}
}
void *mallocm(float **matrix, int x){
int i;
puts("Allocating...");
matrix=(float**) malloc (x*sizeof(float*));
allocheckm(matrix);
for (i=0; i<x; i++){
*(matrix+i) = (float *) malloc (x*sizeof(float));
allocheckl(matrix[i]);
}
puts("Allocated!");
system("PAUSE");
}
void *reallocm(float **matrix, int x){
int i;
matrix=NULL;
matrix = (float**) realloc(matrix, x*sizeof(float*));
allocheckm(matrix);
for (i=0; i<x; i++)
*(matrix+i) = (float*) realloc(matrix[i], x*sizeof(float));
allocheckl(*(matrix+1));
}
void copymatrix(float **v, float **k, int size){
int i, j;
for (i=0;i<size;i++)
for(j=0;j<size;j++)
v[i][j]=k[i][j];
}
float determinant (float **v, int k) {
float **d1, **d2;
int i, j, l;
int size, factor=1, det;
for (i=0;i<k;i++){
det=0;
for(j=0;j<k;j++){
if(v[i][j]!=0) det=1;
if(v[j][i]!=0) det=1;
}
if(!det) break;
}
if (det){
d1 = (float **) malloc (sizeof(float)*k);
if(!d1) exit(1);
d2 = (float **) malloc (sizeof(float)*(k-1));
if(!d2) exit(1);
copymatrix(d1, v, size);
for (size=k; size>1; size--) {
if (d1[0][0]==0) {
for(i=1;i<size;i++)
if (d1[0][i]) break;
for(j=0;j<size;j++){
l=d1[j][0];
d1[j][0]=d1[j][i];
d1[j][i]=l;
}
factor*=-1;
}
if (d1[0][0]!=1){
for(i=0;i<size;i++)
d1[0][i]/=d1[0][0];
factor*=(1/d1[0][0]);
}
for (i=0;i<(size-1);i++)
for(j=0;j<(size-1);j++)
d2[i][j]=(d1[i+1][j+1]-(d1[0][j]*d1[i][0]));
d1=(float **) realloc(d1, sizeof(float)*(size-1));
if(!d1) exit(1);
copymatrix(d1, d2, (size-1));
d2=(float **) realloc(d2, sizeof(float)*(size-2));
if(!d2) exit(1);
}
}
det=d1[0][0]*factor;
free(d1);
free(d2);
return det;
}
void readmat(float **v, int k) {
int i, j, a=0;
float l;
puts("Type the matrix:");
for (i=0;i<k;i++)
for(j=0;j<k;j++) {
scanf("%f", &l);
a++;
printf("\n%d values inserted.\b", a);
v[i][j]=l;
}
}
void showmat(float **v, int k) {
int i, j;
puts("Matrix:");
for (i=0;i<k;i++)
for(j=0;j<k;j++){
printf("%f ", v[i][j]);
if(j==2) printf("\n");
}
}
int main() {
float **mat;
int size;
float det;
do {
printf("Type size of the matriz: ");
scanf("%d", &size);
if (size<1) puts("Wrong size.");
} while(size<1);
mallocm (mat, size);
if (!mat) exit(1);
system("cls");
int i, j, a=0;
float l;
readmat(mat, size);
system("cls");
showmat(mat, size);
det=determinant(mat, size);
printf("\n\ndet(M)=%d", det);
free(mat);
return 0;
}
i didn't have the time to test the determinant algorithm, but i was trying to archive it reducing the size of the matrix to 1. I know it is not the best way, but it is just trial. If i get this code running smooth, I will try to go for Laplace or reducing the matrix to a simpler one.