这是我编写的用于将两个矩阵相乘的程序。
#include <stdio.h>
#include <stdlib.h>
void allocate(int **mat,int m,int n)
{
int i;
mat = (int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++)
*(mat+i) = (int*)malloc(n*sizeof(int));
}
void read(int **mat,int m,int n)
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("Enter the element in row number %d and column number %d\n",i+1,j+1);
scanf("%d",*(mat+i)+j);
}
}
void multiply(int **mat1,int m,int n,int **mat2,int p,int **prod)
{
int i,j,k;
for(i=0;i<m;i++)
for(j=0;j<p;j++)
{
*(*(prod+i)+j) = 0;
for(k=0;k<n;k++)
*(*(prod+i)+j) += (*(*(mat1+i)+k))*(*(*(mat2+k)+j));
}
}
void PRINT(int **mat,int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",*(*(mat+i)+j));
}
printf("\n\n\n");
}
}
int main()
{
int m,n,p,**mat1,**mat2,**prod;
printf("Enter the number of rows of the first matrix to be multiplied\n");
scanf("%d",&m);
printf("Enter the number of columns of the first matrix to be multiplied\n");
scanf("%d",&n);
printf("Enter the number of columns of the second matrix to be multiplied\n");
scanf("%d",&p);
allocate(mat1,m,n);
allocate(mat2,n,p);
allocate(prod,m,p);
printf("Enter the entries of the first matrix\n");
read(mat1,m,n);
printf("Enter the entries of the second matrix\n");
read(mat2,n,p);
printf("The first input matrix is\n");
PRINT(mat1,m,n);
printf("The second input matrix is\n");
PRINT(mat2,n,p);
multiply(mat1,m,n,mat2,p,prod);
printf("The product matrix is\n");
PRINT(prod,m,p);
return 0;
}
scanf
函数定义中使用的read
函数不起作用,它只是不允许我们提供任何输入而意外停止。我在另一个程序中以相同的方式使用它来查找矩阵的轨迹,并且在那里很好。
[请帮助我发现错误。
首先,您忘记包含<stdio.h>
。请把它包括在内。 (您的编译器一定已经警告您,切勿忽略警告!)
第二,您的分配功能非常错误。
当前,您在mat
中分配了局部变量allocate
,并且既不返回也不传递指针==>该值在函数末尾丢失(在c中,参数始终通过值)。因此,您将写入无效数据和程序段错误。
因此,当您分配数据时,必须分配一个指向该数据的指针。这里的数据是int**
。这意味着您的分配函数必须以int***
作为输入。 (您也可以退还垫子)
您的程序应使用:
void allocate(int ***mat,int m,int n)
{
int i;
*mat = (int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++)
*(*mat+i) = (int*)malloc(n*sizeof(int));
}
此外,对于调试此类问题,valgrind下次可能真的很有帮助。