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

标签 c arrays malloc dynamic-allocation

我编写了一个程序来计算动态大小(由用户给定)的数组的算术平均值和协方差,该数组是使用 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时,请使用%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]。由于它包含垃圾值,因此可能是内存不足的位置,从而导致未定义的行为。

关于c - 动态分配数组中的值既不能访问也不能更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215995/

相关文章:

c - "Repassing"函数参数

python - 特定值的 numpy 数组打印索引

C - if/else 语句

c - 尝试将随机生成的 float 存储在数组中。但无法理解为什么数组采用垃圾值

java - 使用泛型创建 Array 对象

Javascript 生成 2 个大小的多维数组

c - 总线错误 : 10 in C Program, 无法找出原因

c++ - 动态创建的数组大小不匹配

c - 用 malloc 解释用户定义的包装器的工作

c - C 中的 fork() 信号子进程和父进程