首页 > 解决方案 > 指针的 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不起作用,它只是不允许我们提供任何输入并意外停止。我在另一个程序中以同样的方式使用它来查找矩阵的踪迹,这很好。

请帮我找出错误。

标签: cpointersscanfmatrix-multiplicationpointer-to-pointer

解决方案


您的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);

您将(当然)需要适当的代码(在某些时候)来释放分配的矩阵。

另外,请参阅Do I cast the result of malloc?


推荐阅读