C 新手,非常感谢您的帮助。
是否可以在 C 中定义数组而不指定其大小或初始化它。
例如,我可以提示用户输入数字并将它们存储在一个 int 数组中吗?我不知道他们会事先输入多少个数字。
我现在能想到的唯一方法是定义一个最大尺寸,这不是一个理想的解决方案......
最佳答案
好吧,你可以动态分配大小:
#include <stdio.h>
int main(int argc, char *argv[])
{
int *array;
int cnt;
int i;
/* In the real world, you should do a lot more error checking than this */
printf("enter the amount\n");
scanf("%d", &cnt);
array = malloc(cnt * sizeof(int));
/* do stuff with it */
for(i=0; i < cnt; i++)
array[i] = 10*i;
for(i=0; i < cnt; i++)
printf("array[%d] = %d\n", i, array[i]);
free(array);
return 0;
}
关于你能在运行时用 C 定义数组的大小吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1591992/