我正在尝试从用户那里获取一些数字,比如说成绩。该代码不起作用,因为 size 在循环中更改为随机数字。我不明白为什么尺寸在用户第一次输入后会得到一个随机值。当我使用数字而不是大小时,一切正常,因此要求成绩的大小会产生这个问题。
#include <stdio.h>
#include <stdlib.h>
float average(int size, float array[size]);
int size;
float array[];
float sum, avg;
int i,j;
int main()
{
printf("Hello there\n enter the number of grades you want to get average\n");
scanf("%d",&size);
printf("\n enter the grades\n");
while(j<size)
{
scanf("%f",&array[j]);
j++;
printf("size and j are %d and %d\n",size,j);
}
return 0;
}
第一次循环后,size 会得到一个随机的大值。
float array[];
Gcc 将假设有 1 个元素数组,并且
size > 1
然后您将访问数组外部的元素。这是一种未定义的行为。您需要有一个可以容纳 size
个元素的数组。