Hello, I'm beginner in C, use kdevelop -> Qt: 3.3.6 KDE: 3.5.4-Red Hat 25.el5.centos.1 KDevelop: 3.3.4
and the compiler is gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)
My doubt is that I made a function (mult_mat_vet) to multiply a matrix (9x9) and a vector (9) and I couldn't return the resulting vector multiplication, within the function I can visualize the result of multiplying, but when the program exits the function tells me that great message: "segmentation fault", I need the y vector to make other important things, sending down the algorithm, summarized, and look forward to your help. Thanks in advance.
Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
float *allocate_vector (int n)
{
float *v;
if (n<1) {
printf("ERROR INVALID PARAMETER!!!");
return (NULL);
}
v=(float *)malloc(n*sizeof(float));
if (v==NULL){
printf("ERROR - NO MEMORY");
return(NULL);
}
else //printf("\nOK!!!\n");
return (v);
}
float **allocate_matrix(int m,int n)
{
float **v;
int i;
if(m<1||n<1)
{
printf("\nINVALID PARAMETER\n");
return(NULL);
}
//aloca as linhas da matriz
v=(float **)calloc(m,sizeof(float *));
if(v==NULL)
{
printf("ERROR - NO MEMORY!!");
return(NULL);
}
for (i=0;i<m;i++)
{
v[i]=(float *)calloc(n,sizeof(float));
if (v[i]=NULL)
{
printf("ERROR - NO MEMORY!!");
return(NULL);
}
}
return(v);
}
float **read_matrix(int *nlin, int *ncol) {
FILE *fr;
float **matriz;
int i, j;
fr = fopen ("ridge.txt", "r");
if (fr == NULL) {
perror("ridge.txt: ");
exit(-1);
}
matriz = (float **) calloc (*nlin, sizeof(float*));
for (i = 0; i < *nlin; i++)
matriz[i] = (float *) calloc(*ncol, sizeof(float));
for (i = 0; i < *nlin; i++)
for (j = 0; j < *ncol; j++)
fscanf(fr, "%f", &matriz[i][j]);
fclose(fr);
return matriz;
}
float *mult_mat_vet(int lin,int col,int linvet, float **mat,float *vetin)
{
int i,j,k;
float *vetout;
vetout=allocate_vector(9);
for(i=0;i<lin;i++)
{
for(j=0;j<col;j++)
vetout[i]=vetout[i]+mat[i][j]*vetin[j];
printf("\nvector %f",vetout[i]); //JUST TO TEST THE MULTIPLICATION!!
}
return(vetout) ;
}
main()
{
float *y,**A;
int nlin,ncol;
/*SYNTHECT VECTOR*/
float Ap[9]={1,0.7,0.2,0.62,1.2,0.9,1,1.08,1.2};
nlin=9;
ncol=9;
A = read_matrix(&nlin, &ncol);
p=Ap;
y=mult_mat_vet(9,9,9,A,p);
printf("\n Don't get here!!!!!!!!!");
//...
//..
//.
//should continue with others commands
return
}