I wrote this code, using dynamic memory allocation for different operations on matrix. In this program when I am calling the inputmatrix(a,r,c)
in the switch case 2 for matrix multiplication then, the compiler is showing me segmentation fault.
code -
#include<stdio.h>
int** inputmatrix(int **a,int r, int c)
{
int i, j;
a = (int**)malloc(r*sizeof(int));
for(i=0; i<c; i++)
{
a[i] = (int*)malloc(sizeof(int));
}
printf("\n Input the Elements of the Matrix :");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d",&a[i][j]);
}
}
return a;
}
int** add(int **a, int **b, int r, int c)
{
int i,j;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
a[i][j] = a[i][j]+b[i][j];
}
}
return a;
}
int** multiplication(int** a, int **b, int r1, int c1, int c2)
{
int **c,i,j,k;
c = (int**)malloc(r1*sizeof(int));
for(i=0; i<c2; i++)
{
c[i] = (int*)malloc(sizeof(int));
}
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j] = 0;
for(k=0; k<c1; k++)
{
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
}
}
return c;
}
int main()
{
int **a, **b,r1,c1,r2,c2, i,j,ch;
int **c;
printf("\n enter your choice : \n1.Addition \n2.Multiplication \n3.Saddle Point \n4. Magic Square \n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n enter the oder of matrix A :");
scanf("%d%d",&r1,&c1);
printf("\n enter the oder of matrix B :");
scanf("%d%d",&r2,&c2);
if(r1==r2 && c1==c2)
{
a = inputmatrix(a,r1,c1);
b = inputmatrix(b,r2,c2);
a = add(a,b,r1,c1);
printf("\n the result of the addition of matrices is :");
for(i=0; i<r1; i++)
{
printf("\n");
for(j=0;j<c1; j++)
{
printf("%d\t",a[i][j]);
}
}
}
else
{
printf("\n these matrices can't be added ");
}
break;
case 2 : printf("\n enter the oder of matrix A :");
scanf("%d%d",&r1,&c1);
printf("\n Enter the Order of Matrix B :");
scanf("%d%d",&r2,c2);
a = inputmatrix(a,r1,c1);
b = inputmatrix(b,r2,c2);
if(c1 == r2)
{
c = multiplication(a, b, r1, c1, r2);
for(i=0; i<r1; i++)
{
printf("\n");
for(j=0; j<c2; j++)
{
printf("%d\t",c[i][j]);
}
}
}
else
{
printf("\n Sorry, These Matrices Can't be Multiplied ");
}
break;
default : printf("\n Sorry, This is a Wrong Choice ");
}
return 0;
}
The main problem is with this segment -
case 2 : printf("\n enter the oder of matrix A :");
scanf("%d%d",&r1,&c1);
printf("\n Enter the Order of Matrix B :");
scanf("%d%d",&r2,c2);
a = inputmatrix(a,r1,c1);
b = inputmatrix(b,r2,c2);
if(c1 == r2)
{
c = multiplication(a, b, r1, c1, r2);
for(i=0; i<r1; i++)
{
printf("\n");
for(j=0; j<c2; j++)
{
printf("%d\t",c[i][j]);
}
}
}
Here when I made this inputmatrix()
function to be called outside the switch of case 2 then, there is no segmentation fault.