C语言 当数组长度未知时,如何用用户输入值填充 C 中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13969144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fill an array in C with user input values, when the array is of unknown length
提问by asterix obelisk
Possible Duplicate:
Dynamic array using ANSI C
可能的重复:
使用 ANSI C 的动态数组
I am trying to fill an array with the values that the user is typing. However, I do not know in advance how many values will my array have, or how many values the user will type in. The user types in a value at a time, the value is stored in the array, and then the user is again prompted to type in another value, and so forth, until he types in a negative number. When the user types in a negative number, the program prints out all the positive values that the user has entered so far (NOT the negative one, as it is essentially only used for termination of the program).
我正在尝试用用户输入的值填充数组。但是,我事先不知道我的数组会有多少个值,或者用户将键入多少个值。用户一次键入一个值,该值存储在数组中,然后用户再次输入提示输入另一个值,依此类推,直到他输入一个负数。当用户输入负数时,程序会打印出用户迄今为止输入的所有正值(不是负数,因为它本质上仅用于终止程序)。
My problem is:
我的问题是:
1) how to declare the array without knowing in advance how big it will be?
1)如何在事先不知道数组有多大的情况下声明数组?
2) how to scan for the user input? For example, I am thinking something like this for scanning the input and assigning the values to the array (this is just a part of the code, not all of it, I just want to know if this part of the code will work when I have completed the program):
2)如何扫描用户输入?例如,我正在考虑这样的事情来扫描输入并将值分配给数组(这只是代码的一部分,不是全部,我只是想知道这部分代码在我已完成程序):
...
...
int working = 0;
int i = 0;
do
{
printf("Enter a positive value \n");
scanf("%d",&x);
if (x >= 0)
{
&array[i] = x;
i++;
}
else
{
printf("You have entered a negative number \n");
working = 1;
}
} while (working = 0);
Is this code correct (of course, it is not a complete program)? Also, how do I declare the array, without knowing how big it will be (I have no way of knowing in advance how many positive values the user will type in before he types in a negative one)
这段代码是否正确(当然,它不是一个完整的程序)?另外,如何在不知道数组有多大的情况下声明数组(我无法提前知道用户在输入负值之前将输入多少正值)
回答by Sergej Christoforov
You can allocate an initial array for user input and save it's size into a variable so then you can reallocate the array when it's full. Or you could use linked list to save input, so later you could calculate needed element count and allocate the array.
您可以为用户输入分配一个初始数组,并将其大小保存到一个变量中,这样您就可以在数组已满时重新分配该数组。或者您可以使用链表来保存输入,以便稍后您可以计算所需的元素数并分配数组。
回答by maverik
int arraySize = 256; // Or whatever
int *array = malloc(arraySize * sizeof(int));
if (!array)
{
fprintf(stderr, "Master, please buy more RAM, I can't allocate memory\n");
return;
}
int numberOfElements = 0;
for(;;)
{
printf("Enter a positive value:\n");
scanf("%d",&x);
if (x >= 0)
{
if (numberOfElements == arraySize)
{
arraySize *= 2; // Or whatever strategy you need
array = realloc(array, arraySize * sizeof(int));
if (!array)
{
fprintf(stderr, "Master, please buy more RAM, I can't allocate memory\n");
break;
}
}
array[numberOfElements++] = x;
}
else
{
printf("You have entered a negative number \n");
break;
}
}
Something like. Sorry for the possible mistakes, don't check it.
就像是。很抱歉可能的错误,不要检查它。
回答by theharshest
Better use linked list, array won't help you here.
最好使用链表,数组在这里帮不了你。
Check this out if you are not familiar with it - http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
如果您不熟悉它,请查看它 - http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
回答by user2000
int dataarray [2];
int no;
int count =0;
while(1)
{
printf("Enter No's = ");
scanf("%d",&no);
if(no<0)
break;
*(dataarray+count)=no;
count++;
}
you can use the count further to know how many elements in array.
您可以进一步使用计数来了解数组中有多少个元素。
you can get elements from this array by pointers link
您可以通过指针链接从此数组中获取元素
no = *(dataarray+count)
回答by dariyoosh
You can use a linked list structure for that. There can be many possible implementations (simple linkedlist, double linkedlist ,etc) if you google you can find many pages about this. Here is an example (not necessarily the most optimized form, but just to give you an idea)
您可以为此使用链表结构。可以有很多可能的实现(简单链表、双链表等),如果你谷歌你可以找到很多关于这个的页面。这是一个例子(不一定是最优化的形式,只是给你一个想法)
#include <stdio.h>
#include <stdlib.h>
struct datalist
{
int value;
struct datalist *next;
};
typedef struct datalist *linkedList;
void addToList(linkedList *param_valueList, const int param_newValue)
{
if (*param_valueList == NULL)
{
linkedList newItem = (linkedList)malloc(sizeof(struct datalist));
newItem->value = param_newValue;
newItem->next = NULL;
*param_valueList = (linkedList)malloc(sizeof(linkedList));
*param_valueList = newItem;
}
else
{
linkedList newList = (linkedList)malloc(sizeof(struct datalist));
newList->value = param_newValue;
newList->next = NULL;
linkedList tmpList = *param_valueList;
while (tmpList->next != NULL)
tmpList = tmpList->next;
linkedList *listPtr = &tmpList;
(*listPtr)->next = newList;
}
}
void printList(const linkedList param_valueList)
{
linkedList tmpList = param_valueList;
while (tmpList != NULL)
{
printf("%d\n", tmpList->value);
tmpList = tmpList->next;
}
}
int main(int argc, char *argv[])
{
int inputNmbr = 0;
linkedList numberList = NULL;
while (1)
{
printf("print a number: ");
scanf("%d", &inputNmbr);
if (inputNmbr > 0)
addToList(&numberList, inputNmbr);
else
break;
}
printf("Here are the numbers you entered:\n");
printList(numberList);
return 0;
}
Regards,
问候,

