【发布时间】:2021-05-27 13:53:48
【问题描述】:
我正在做一个学校项目。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
float addNumbers(float *array){
float t;
int len = sizeof(array) / sizeof(array[0]);
for(int i = 0; i < len;i++){
t += array[i];
}
return t;
};
int main(){
float n;
float* v = (float*)malloc(10 * sizeof(float));
int counter = 1;
for(int i = 0;i < 4;i++){
printf("Insert N%d: ", counter);
counter++;
scanf("%f", &n);
v[i] = n;
printf("%f\n", n);
}
int len = sizeof(v) / sizeof(v[0]);
for(int i = 0;i < len;i++){
printf("%f", v[i]);
}
free(v);
float x = addNumbers(v);
printf("%f", x);
}
这段代码的输出是:
Insert N1: 5
5.000000
Insert N2: 7
7.000000
Insert N3: 8
8.000000
Insert N4: 3
3.000000
5.000000-1.#QNAN0
我发现问题在于数组如何存储值。插入 N$ 下方的值是 n 的值。 5.000000-1.#QNAN0 然而,
是存储在数组中的值,但它只有一个。我决定给数组更多的内存,但这不起作用。我知道的就这些了
【问题讨论】:
-
int len = sizeof(array) / sizeof(array[0]);这是不正确的。这个函数AddNumbers不能从float *推导出大小。调用函数时必须提供大小。 -
len是 10 - 无需使用sizeof“计算”它。最好在开头添加#define LEN 10,并将malloc中的len和10替换为LEN。