C中的数组可以定义为根据用户的输入进行调整吗?

标签 c arrays input

#include <stdio.h>
#include <math.h>

int main()
{
    int i = 0, num[10], termnum = 0;

    return 0;
}

大家好,我正在尝试计算平均值并接受用户的数字。 我想存储索引以将信息用于其他用途。 所以用户可以输入数字直到“-1”,然后停止。 我可以调整数组吗?

例如int num[i],i=0;?

最佳答案

如果您知道数组大小在运行时已知并且相当小,则可以使用可变长度数组。

size_t len;
scanf("%zu", &len);
int arr[len];

VLA 的问题是无法捕获分配失败。例如,如果 len 非常大,那么 arr 分配可能会失败,直到它爆炸你才会知道。此外,从 C11 开始,VLA 支持是可选的。

但是如果你想在不知道总数的情况下连续输入数字,那么你可以根据需要使用 mallocrealloc() 进行动态内存分配:

size_t n = 16; //arbitrary start size
int *arr = arr(n * sizeof *arr);

while(..) {
  //read input here
  // realloc "arr" if number of inputs go beyond "n"
}

另一方面,如果您不需要数字而只对平均值感兴趣,那么您根本不需要任何数组。只需阅读数字并在阅读时计算总数:

int total = 0;
int num = 0;
size_t n = 0;

  while(scanf("%d", &num) == 1) && num != -1) {
     total += num; // need to take care of integer overflow!
     n++;
  }

关于C中的数组可以定义为根据用户的输入进行调整吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33835278/

相关文章:

html - 我做错了什么? CSS输入类型文件并提交

c# - 将输入设置为默认音频设备 ( SetInputToDefaultAudioDevice() )

c - 本程序的控制流程

ios - 使数组中的 3 个随机元素不可见

Javascript 最大值和最小值不起作用

c++ - 数组初始化知识

mysql - mysql中如何将列转换为数组?

c - c数组编程

C语言-if语句问题

c - 指针运算出错