我编写了一个程序来计算动态大小(由用户给定)的数组的算术平均值和协方差,该数组是使用 malloc 声明的,但该程序没有打印预期的输出。因此,我使用断点来观察数组中的值,发现这些值没有改变。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
void main()
{
int n;
printf("enter n: \n");
scanf("%d", &n);
double sum = 0, m, spv;
double *x = (double *)malloc(sizeof(double)*n);
for (int i = 0; i < n; ++i)
{
scanf("%f", x[i]);
sum += x[i];
}
m = sum / n;
printf("Mittel = %f\n", m);
sum = 0;
for (int i = 0; i < n; ++i)
{
sum += pow((x[i] - m), 2);
}
spv = sum / (n - 1);
printf("SPV = %f\n", spv);
free(x);
return;
}
最佳答案
scanf("%f", &x[i]);
您需要传递地址。
还要检查malloc
的返回值。并且不要强制转换 malloc
的结果。
当您阅读double
时,请使用%lf
。 scanf("%lf",&x[i]);
double *x = malloc(sizeof(double)*n);
if( x == NULL){
fprintf(stderr,"%s","Error in malloc");
exit(1);
}
根据标准 (c99)(§7.21.6.9)
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
如果不使用 &
,scanf
将尝试写入由 x[i]
表示的内存位置,而不是 &x [i]
。由于它包含垃圾值,因此可能是内存不足的位置,从而导致未定义的行为。
关于c - 动态分配数组中的值既不能访问也不能更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215995/