你能在运行时用C定义数组的大小 [英] Can you define the size of an array at runtime in C
本文介绍了你能在运行时用C定义数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
新的C,非常感谢帮助。
New to C, thanks a lot for help.
是否有可能在C中定义阵列时不指定任何它的大小或对其进行初始化。
Is it possible to define an array in C without either specifying its size or initializing it.
例如,我可以提示用户输入数字,并将其存储在一个int数组?我不知道他们有多少人数将事先输入。
For example, can I prompt a user to enter numbers and store them in an int array ? I won't know how many numbers they will enter beforehand.
我现在能想到的唯一的办法是定义一个最大尺寸,这不是一个理想的解决方案...
The only way I can think of now is to define a max size, which is not an ideal solution...
推荐答案
好了,你可以动态分配的大小:
Well, you can dynamically allocate the size:
#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定义数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文