You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言用指针和malloc实现矩阵加减报lvalue required错误原因

错误原因分析

你遇到的编译错误本质是赋值运算符左侧使用了不可被修改的右值,核心问题出在矩阵元素的指针寻址逻辑错误:

  • 你使用单指针double *a将二维矩阵平铺存储为一维连续内存,定位第i行第j列元素的正确计算逻辑是:元素偏移量为i * 列数 + j,对应的取值写法为*(a + i * col + j),对应的取地址写法为a + i * col + j。
  • 你代码中写的(*(a + i) + j)逻辑完全错误:a是double*类型,a + i是向后偏移i个double长度的地址,解引用*(a + i)得到的是一个double类型的数值,再加上j得到的是临时计算出来的数值(属于右值),既不能作为scanf要求传入的地址参数,也不能放在赋值运算符左侧被赋值,因此编译器抛出lvalue required as left operand of assignment错误。
代码修正方案

你需要将所有寻址相关的代码替换为正确的偏移逻辑,修正后的完整代码如下:

#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));
    // 新增内存分配失败判断,避免崩溃
    if(a == NULL || b == NULL || c == NULL || d == NULL) {
        printf("内存分配失败");
        return 1;
    }

    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 * col + 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 * col + j);
        }
    }
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            // 赋值左侧使用可修改的内存地址对应值
            *(c + i * col + j) = *(a + i * col + j) + *(b + i * col + j);
        }
    }
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            *(d + i * col + j) = *(a + i * col + j) - *(b + i * col + j);
        }
    }
    printf("A+B=\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%lf ",*(c + i * col + j));
        }
        printf("\n");
    }
    printf("A-B=\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%lf ",*(d + i * col + j));
        }
        printf("\n");
    }
 
    // 释放堆内存,避免内存泄漏
    free(a);
    free(b);
    free(c);
    free(d);
    return 0;
}
额外优化说明
  • 生产环境中malloc申请内存后必须判断返回值是否为NULL,避免内存分配失败导致程序崩溃
  • 堆内存申请使用完成后必须调用free释放,避免出现内存泄漏问题

内容的提问来源于stack exchange,提问作者Sassy Math

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 18:27:03