c - 在C中初始化未知大小的数组

标签 c arrays

我有这段代码:

#include <stdio.h>

int average(int array []);

int main () {

int num_array[];


int x = 0;

  while(num_array[x] != -1){

     printf("Enter a number\n");
     scanf("%d",&num_array[x]);

     x++;

  }

  printf("%d\n", average(num_array));

  return 0;
}



int average(int array[]){

  int i;
  int total_size = (int)sizeof(array);
  int sum = 0;

  for(i = 0; i < total_size; i++){

    sum = sum + array[i];

  }

  return sum/total_size;

}

但是我在编译时收到错误,因为我没有初始化数组。但是我做不到,因为我不知道它的大小。

我该如何解决这个问题?

最佳答案

你不能像这样声明一个数组

int num_array[];  

在 C 中,除非它是函数的参数。您必须指定尺寸。

关于c - 在C中初始化未知大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880610/

相关文章:

c++ - 结合 CMake option() 与 add_definitions()

c - 使用递归打印控制台 "picture"

C++ 多维 vector 追加

javascript - 使用 javascript 获取复选框属性(数组)

c - 忽略空的可变参数

c - 操纵变量的地址来存储较小的类型?

c - 使用 Poppler 获取指定目的地的 "name"

C如何在unsigned int指针之间进行异或

php - 如何在codeigniter中将数组创建为数组

python - NumPy 中 astype 的有效参数