动态分配数组中的值既不能访问也不能更改

the values in a dynamic allocated array can be neither accessed nor changed

我编写了一个程序来计算一个动态大小的数组(由用户给定)的算术平均值和协方差,该数组是使用 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 的 return 值。并且不要转换 malloc.

的结果

在您阅读 double 时使用 %lfscanf("%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] 表示的内存位置。由于它包含垃圾值,它可能是内存不足的位置,导致未定义的行为。

scanf 需要地址作为参数

改变这个

scanf("%f", x[i]);

scanf("%f", &x[i]);

是的,“%f”->“%lf”