c - 使用动态内存分配的矩阵加法和减法
问题描述
我被要求使用 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;
}
现在每当我运行它时,编译器都会不断向我展示
[错误] 需要左值作为赋值的左操作数
我将数组作为用户可以插入任何实数的两倍。
为什么会这样显示?
解决方案
因为(*(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;
}
推荐阅读
- python - python threading.Thread函数返回问题
- javascript - 计算行长时有没有办法忽略缩进?
- selenium - 独立运行时的 Selenium Grid 关闭命令
- laravel - Voyager Bread 更新函数 URL
- hibernate - 使用 JPA CriteriaBuilder 时保留 @ManyToMany 的 @OrderColumn 信息
- powershell - PowerShell 在同一行显示属性
- javascript - 如何获取页面 qweb 报告中的行数。奥多 11
- node.js - Firestore 子集合与 mongodb 子文档
- javascript - 在反应中从javascript文件加载图像的问题
- wpf - 如何使用 AttachedCommandBehavior 将多个事件绑定到 setter 样式?