Himanshu Sourav - 1 year ago 82
C Question

# Matrix Multiplication for any proper order with dynamic memory allocation

I am trying to perform matrix multiplication(dynamic memory allocation) where that the user can enter any valid order for matrix multiplication (i.e. column1=row2).
The output for same orders (2x2 or 3x3) for both matrices result in proper computation, but the orders like mat1 2x3 & mat2 3x2..give segmentation fault. I am not able to ascertain how am I accessing any illegal memory when I am doing the memory allocation beforehand.

kindly advise, pls forgive me if I am making some silly mistake...

following is the complete code:

``````#include<stdio.h>
#include<stdlib.h>

main(){
int **mat1, **mat2,**res,i,j,r1,c1,r2,c2;

printf("\nEnter the Order of the First matrix...\n");
scanf("%d %d",&r1,&c1);
printf("\nEnter the Order of the Second matrix...\n");
scanf("%d %d",&r2,&c2);

if(c1!=r2){
printf("Invalid Order of matrix");
exit(EXIT_SUCCESS);
}

mat1= (int**) malloc(r1*sizeof(int*));

for(i=0;i<c1;i++)
mat1[i]=(int*)malloc(c1*sizeof(int));

mat2= (int**) malloc(r2*sizeof(int*));

for(i=0;i<c2;i++)
mat2[i]=(int*)malloc(c2*sizeof(int));

res=(int**)calloc(r1,sizeof(int*));

for(i=0;i<c2;i++)
res[i]=(int*)calloc(c2,sizeof(int));

//Input Matrix1
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&mat1[i][j]);
//Input Matrix2
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&mat2[i][j]);

//Printing Input Matrix 1 and 2

printf("\n Entered Matrix 1: \n");
for(i=0;i<r1;i++){
for(j=0;j<c1;j++)
printf("%d ",mat1[i][j]);
printf("\n");
}

printf("\n Entered Matrix 2: \n");
for(i=0;i<r2;i++){
for(j=0;j<c2;j++)
printf("%d ",mat2[i][j]);
printf("\n");
}

//Computation

//Multiplication

for(i=0;i<r1;i++){
for(j=0;j<c2;j++){
res[i][j]=0;
for(k=0;k<c1;k++)
res[i][j]+= mat1[i][k]*mat2[k][j];

}
printf("\n");
}

printf("\nThe Multiplication of two matrix is\n");
for(i=0;i<r1;i++){
printf("\n");
for(j=0;j<c2;j++)
printf("%d\t",res[i][j]);
}
printf("\n");

for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
res[i][j]=mat1[i][j]+mat2[i][j];

printf("\nThe Addition of two matrix is\n");
for(i=0;i<r1;i++){
printf("\n");
for(j=0;j<c2;j++)
printf("%d\t",res[i][j]);
}
*/

return 0;}
``````

``````mat1= (int**) malloc(r1*sizeof(int*));

for(i=0;i<c1;i++)  < c1 instead of r1
mat1[i]=(int*)malloc(c1*sizeof(int));

mat2= (int**) malloc(r2*sizeof(int*));

for(i=0;i<c2;i++)   < c2 instead of r2
mat2[i]=(int*)malloc(c2*sizeof(int));
``````

You use c1/2 in your `for` instead of r1/2.

If r1 < c1, you end up outside of the memory you allocated.

If r1 > c1, you end up with uninitialized pointers.

Not related to the issue but you should write `int main()` instead of `main()`, the second one is accepted but the first one easier to read.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download