c - 指针的 scanf 函数不起作用(对于使用指针指针的矩阵)
问题描述
这是我编写的用于将两个矩阵相乘的程序。
#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
不起作用,它只是不允许我们提供任何输入并意外停止。我在另一个程序中以同样的方式使用它来查找矩阵的踪迹,这很好。
请帮我找出错误。
解决方案
您的allocate
函数接收传递的副本作为int **
其第一个参数,因此,在您的函数中用作此参数的变量main
不会被它修改。
为了解决这个问题,您可以将参数作为“指向 int** 的指针”(即int*** mat
)传递 - 但这开始变得混乱(您需要allocate
相应地调整内部代码)。更好的方法是重新定义allocate
函数以返回创建的指针,如下所示:
int** allocate(int m, int n)
{
int i;
int** mat = malloc(m * sizeof(int*));
for (i = 0; i < m; i++)
*(mat + i) = malloc(n * sizeof(int));
return mat;
}
然后,在您的main
函数中,将调用修改allocate
如下:
mat1 = allocate(m, n);
mat2 = allocate(n, p);
prod = allocate(m, p);
您将(当然)需要适当的代码(在某些时候)来释放分配的矩阵。
推荐阅读
- reactjs - 如何使用 clearInterval 暂停计时器
- vue.js - 在 Vue3 和 Vue-router 中获取当前路由的最佳方法?
- c++ - 请帮我解决这个 c++ 代码中的错误
- swift - 纹理(AsyncDisplayKit)图像闪存
- javascript - D3 在本地保存 JSON 文件
- html - 验证国家代码并删除国家代码后的 0(如果输入类型 tel html5 中存在)
- excel - 如何按名称删除带有 VBA 的 ActiveX 按钮?
- python - 将 rpyc 远程 stdio 重定向到流
- python - 如何从枢轴操作合并回数据框?
- parse-platform - 如何为数组字段中的指针添加权限指针?