【发布时间】:2020-09-22 13:17:45
【问题描述】:
我需要使用 指针数组 来将 2 个矩阵相乘。它的工作,但我得到错误的输出
.如果我给出 m1=n1=m2=n2 = 2 并且两个矩阵都为1 2 3 4。我得到的 o/p 矩阵为7 17 32 54,而正确答案是7 10 15 22。请帮助我,我在这里停留了 2 天...................................................... ....................................
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m1,n1,m2,n2,i,j,k,sum=0,*a[10],*b[10],*c[10];
printf("Enter m1 and n1 : ");
scanf("%d%d",&m1,&n1);
printf("Enter m2 and n2 : ");
scanf("%d%d",&m2,&n2);
if(n1==m2)
{
for(i=0;i<m1;i++)
{
a[i] = (int *)malloc(n1*sizeof(int));
}
for(i=0;i<m2;i++)
{
b[i] = (int *)malloc(n2*sizeof(int));
}
for(i=0;i<m1;i++)
{
c[i] = (int *)malloc(n2*sizeof(int));
}
printf("Enter the first matrix : ");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
scanf("%d",(*(a+i)+j));
}
}
printf("Enter the second matrix : ");
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
scanf("%d",(*(b+i)+j));
}
}
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
for(k=0;k<n2;k++)
{
sum += a[i][k] * b[k][j];
}
*(*(c+i)+j) = sum;
}
}
printf("The Resultant Matrix : ");
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
printf("%d ",*(*(c+i)+j));
}
printf("\n");
}
}
else
printf("Invalid Matrix\n");
}
【问题讨论】:
-
因为这是
C,所以这个表达式(以及其他类似的):a[i] = (int *)malloc(n1*sizeof(int));应该表示为a[i] = malloc(n1*sizeof(int));,因为it is not recommeded to cast the return of malloc() and family in C -
但是我不能以任何其他方式使用指针数组并且类型转换工作正常,因为当我打印 2 个数组 a 和 b 时我得到
1 2 3 4 -
但是我不能使用指针数组。真的吗?
标签: c