【发布时间】:2019-12-29 20:54:20
【问题描述】:
我在 Xcode 版本 11.2 上运行此代码。我有一个包含 5 行和 3 个列的矩阵,我想计算每行的平均值。现在我在这里尝试对其进行编码,但我的矩阵似乎始终为空,并且我在s= s +aloc[i*5+j]; 收到此错误Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)。我不知道我应该在我的代码中修改什么以便它工作。你能帮帮我吗?
#include <stdio.h>
#include <stdlib.h>
void reads(float *aloc);
void amount(float *aloc);
void done(float *aloc);
int main()
{
float *aloc = NULL;
reads(aloc);
amount(aloc);
done(aloc);
return 0;
}
void reads(float *aloc)
{
if ((aloc = (float*)malloc(5 * sizeof(float))))
{
for (int i = 0; i < 5; i++)
{
printf("\n Enter the values for the row no. %d : ",1+i);
for(int j=0;j<3;j++)
scanf("%f", aloc + i*5+j);
}
}
}
void amount(float *aloc)
{
float s;
int j,i;
for(i=0;i<5;i++)
{ s=0;
for(j=0;j<3;j++)
s= s +aloc[i*5+j];
printf("\n The average of the row no. %d is : %.2f ",i+1,s/3.);
}
}
void done(float *aloc)
{
free(aloc);
}
【问题讨论】:
-
aloc + i*5+j。您尚未为行分配内存。 -
将 aloc 中的 NULL 传递给 read(aloc) 有什么意义?这并不像你认为的那样。 main() 中的 aloc 与被调用函数中的 aloc 参数不同。
-
OT:为了便于阅读和理解:请始终缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格。
-
关于:
for(j=0;j<3;j++)这只会循环语句:s= s +aloc[i*5+j];可能不是你想要的。
标签: c