I’m facing segmentation fault problem when trying to run this code:
#include<stdio.h>
#include<stdlib.h>
int mallocMatrix (int ***matrix, int A, int B) {
int i;
*matrix=(int**)malloc(sizeof(int*)*B);
for(i=0;i<A;i++)
(*matrix)[i]=(int*)malloc(sizeof(int)*A);
};
void fillMatrix (int ***matrix, int A, int B) {
int i, j;
for(i=0;i<B;i++)
{
for(j=0;j<A;j++)
{
printf("Matrix[%d][%d]: ",i+1,j+1);
scanf("%d", &(*matrix)[i][j]);
}
}
};
void displayMatrix (int ***matrix, int A, int B) {
int i, j;
printf ("\n");
for(i=0;i<B;i++)
{
for(j=0;j<A;j++)
{
printf ("%d ", (*matrix)[i][j]);
}
printf ("\n");
}
};
int main(){
int **matrix;
int **matrix_two;
int **matrix_three;
int a, b, c, d;
printf ("[1st matrix] number of columns:");
scanf ("%d", &a);
printf ("[1st matrix] number of rows:");
scanf ("%d", &b);
mallocMatrix (&matrix, a, b);
fillMatrix (&matrix, a, b);
printf ("[2nd matrix] number of columns:");
scanf ("%d", &c);
printf ("[2nd matrix] number of rows:");
scanf ("%d", &d);
if (a==d)
{
mallocMatrix (&matrix_two, c, d);
fillMatrix (&matrix_two, c, d);
}
else
{
printf ("The number of columns of the 1st. matrix must be equal to the number of rows of the 2nd. matrix");
return -1;
}
displayMatrix (&matrix, a, b);
displayMatrix (&matrix_two, c, d);
mallocMatrix (&matrix_three, b, c);
/* multiplication */
int i, j, k;
for(i = 0; i < b; i++)
{
for(j = 0; j < c; j++)
{
for(k = 0; k < b; k++)
{
matrix_three[i][j] = matrix_three[i][j] + matrix[i][k] * matrix_two[k][j];
}
}
}
/* end of multiplication */
displayMatrix (&matrix_three, b, c);
}
Problem pops up after code signed /multiplication/. For example:
– first matrix is 2×2,
– second 3×2.
I’m expecting result as 3×2 matrix, BUT code gives me 2×2 matrix and segmentation fault when trying to reach third column. Please, point error
I think i found your mistake in mallocMatrix:
The loop condition is wrong you said that B is row count, so for every rouw you must alloc an array of A elements so, the loop should be:
so when you try 3×2 the third row is never initialized because your loop just iterates 2 times, and when you try to fill the last row crashes