首页 > 解决方案 > 使用动态内存分配的矩阵加法和减法

问题描述

我被要求使用 C 中的指针和函数来加减两个二维矩阵malloc()。这是我的代码。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i,j,row,col,n;
    double *a,*b,*c,*d;
 
    printf("Enter the number of rows: ");
    scanf("%d",&row);
    printf("Enter the number of columns: ");
    scanf(" %d",&col);
    n=row*col;
    a = (double *) malloc(n*sizeof(double));
    b = (double *) malloc(n*sizeof(double));
    c = (double *) malloc(n*sizeof(double));
    d = (double *) malloc(n*sizeof(double));
    printf("Enter the numbers of First Matrix, A:\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            scanf("%lf", (*(a + i) + j));
        }
    }
    printf("Enter the numbers of Second Matrix, B:\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            scanf("%lf", (*(b + i) + j));
        }
    }
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            (*(c + i) + j) = (*(a + i) + j) + (*(b + i) + j);
        }
    }
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            (*(d + i) + j) = (*(a + i) + j) - (*(b + i) + j);
        }
    }
    printf("A+B=\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%lf ",(*(c + i) + j));
        }
        printf("\n");
    }
    printf("A-B=\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%lf ",(*(d + i) + j));
        }
        printf("\n");
    }
 
 
    return 0;
}

现在每当我运行它时,编译器都会不断向我展示

[错误] 需要左值作为赋值的左操作数

在此处输入图像描述

我将数组作为用户可以插入任何实数的两倍。

为什么会这样显示?

标签: cpointersmultidimensional-arraydynamic-memory-allocation

解决方案


因为(*(c+i)+j)是like c[i]+j,所以你的左边不是左值。例如,如果您的矩阵c是 [[1,2],[3,4]],那么它与 2(*(c+0)+1)相同c[0]+1,然后您尝试这样做2 = something,您会得到该错误。要解决这个问题,首先您需要将*括号外移,但即便如此,您的逻辑也有点缺陷。你想使用类似的东西*(c+col*i+j)

此代码将矩阵作为输入并打印它,尝试查看我如何使用指针并将其应用于您的代码。

#include <stdio.h>
#include <stdlib.h>
int main(){
    int i,j,row,col,n;
    double *a;

    printf("Enter the number of rows: ");
    scanf("%d",&row);
    printf("Enter the number of columns: ");
    scanf(" %d",&col);
    n = row*col;

    a = (double *) malloc(n*sizeof(double));

    printf("Enter the numbers of First Matrix, A:\n");
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            scanf("%lf", (a+ col*i + j));
        }
    }

    printf("A:\n");
    for(i=0; i<row; i++){
        for(j=0; j<col;j++){
            printf("%lf ", *(a+ col*i + j));
        }
        printf("\n");
    }

    free(a);
    return 0;
}

推荐阅读