我编写了这段代码,使用动态内存分配对矩阵进行不同的操作。在这个程序中,当我在切换案例2中调用inputmatrix(a,r,c)
进行矩阵乘法时,编译器会向我显示分段错误。
代码 -
#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;
}
主要问题在于这一部分 -
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]);
}
}
}
这里,当我在案例2的切换之外调用此inputmatrix()
函数时,没有分段错误。