如何声明数组与任意大小 [英] How to declare an array with an arbitrary size
问题描述
好吧,这是一个C语言编程作业的问题。但我确实被卡死。
Ok, this is a C programming homework question. But I'm truly stuck.
我要求用户输入文字,然后我插入输入到一个数组,但我不能有超过的话的用户类型数的任何控制。
I ask the user to input words, and then I insert the input into an array, but I can't have any control over the number of words the user types.
我猜我问的是你如何申报在C数组没有宣布它的长度和不要求用户的长度应该是什么。
I guess what I'm asking is how do you declare a an array in C without declaring its length and without asking the user what the length should be.
我知道这牵扯到使用malloc,但是如果你能给我如何做到这一点的一些例子,我真的AP preciate它。
I know this has something to do with malloc, but if you could give me some examples of how to do this, I would really appreciate it.
推荐答案
您可以像每次realloc的吧:
You can realloc it every time like:
int size = 0;
char **array = malloc(0);
while(/* something */)
{
char *string = // get input
size++;
array = realloc(array, size * sizeof(char*));
array[size - 1] = string;
}
或在块,如果你关心速度。
Or in chunks if you care about speed.
这篇关于如何声明数组与任意大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!