数组输入而不询问数组元素的数量

时间:2016-04-29 23:32:39

标签: c

int array[], n;

printf("Enter number of elements\n");
scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)
  scanf("%d", &array[c]);

以上是我用来向数组输入值的代码,但有没有办法给数组提供输入值而不要求用户输入数组中元素的数量?

4 个答案:

答案 0 :(得分:2)

是的,两个最常见的选项是使用realloc to resize the array as needed,也就是动态大小的数组,或使用称为linked list的不同数据结构。它们各有利弊。

链表是一组数据节点,它们与下一个节点(如果它是前面的双链表)连接。类似的东西:

typedef struct {
    int value;
    Node *next;
} Node;

这使得在任何地方添加新元素变得非常容易,即使在中间也是如此。但是要转到第n个节点需要遍历整个列表。

另一个选项是跟踪数组的大小,并在需要更多空间时调用reallocrealloc将增加分配给数组的内存。它可能必须通过将所有内容复制到新的内存位置来完成此操作,因此您不希望经常这样做;通常你分配的比你需要的多。

除动态大小外,这具有常规数组的所有优点和缺点。但它仍然需要您跟踪数组的已分配大小并根据需要调整大小,因此您需要一个结构来存储数组,它的大小和元素的大小,以及一些控制访问的函数。 / p>

C没有这些作为内置插件。你可以自己实现它们作为练习,它是教育性的,任何体面的算法和数据结构书都会为它们练习。但是对于生产用途,我建议使用第三方库,因为它们将被很好地记录,优化和测试。有任何可用的号码,我建议从Gnome Lib开始,因为它提供了大量缺失的C基础知识,如哈希,正则表达式,队列,更好的字符串处理,树... ...

答案 1 :(得分:1)

这是一个为数组动态分配空间并根据需要扩展它的方法:

#define SIZE 16        // initial size of the array
...
size_t arraySize = 0;  // Number of elements allocated for array
size_t count = 0;      // Number of elements used

int *array = malloc( sizeof *array * SIZE ); // initial allocation
if ( array )
  arraySize = SIZE;
else
  // error allocating memory, handle as appropriate

while ( !done )
{
  if ( count == arraySize ) // we need to extend the array
  {
    int *tmp = realloc( array, sizeof *array * (2 * arraySize) ); // double the size
    if ( !tmp )
      // error extending array, handle as appropriate
    else
    {
      arraySize *= 2;
      array = tmp;
    }
  }
  array[count++] = new_value;
}

答案 2 :(得分:0)

不要求整数,而是要求用户输入以逗号分隔的值列表作为字符串。

然后您将该字符串视为获取,验证并计算所有值。

答案 3 :(得分:0)

如果我理解你的问题,你想知道你是否可以简单地要求用户输入数据来填充数组而不首先确定数组大小?

如果这确实是你想要的,那么答案就是否定。在c中,必须先声明数组的大小,然后才允许向其中添加数据。但是,使用结构可以解决此问题。

您可以定义这样的结构:

#define BUFSIZE 1024
typedef struct dynamic_array {
  int buffer[BUFSIZE]; // or whatever initial size you want
  int current_index;   // the index where the next data element should be inserted
  int buffer_size;     // this will initially equal BUFSIZE but could change
} dynamic_array;

如果你声明这个结构,那么你只需要定义函数来初始化你的数组,插入你的数组,删除,搜索等。当你插入一个元素时,你需要检查你的current_index&lt; ; BUFSIZE。代码大纲如下所示:

function insert(dynamic_array *arr, int data) {
  if (arr->current_index < BUFSIZE) {     //your buffer has space!
    // add element to array
  }
  else { 
    // create new array that is twice the size of the old array and copy the data from the old array to the new array.
  }
} 

使用此方法或类似方法,您只需通过dynamic_array结构将数据插入到数组中,而无需担心在给定初始数组大小的情况下添加过多数据。