【问题标题】:How to expand a one-dimensional array at runtime in C?如何在 C 中运行时扩展一维数组?
【发布时间】:2014-04-16 22:32:21
【问题描述】:

我正在学习 C 语言,我有一个关于动态内存分配的问题。
考虑到我有一个程序,用户必须输入数字或键入字母“E”才能退出程序。 用户输入的数字必须存储在一维数组中。此数组以单个位置开始。
如何将我的整数数组增加到用户输入的每个数字以将此数字存储在这个新位置?我想我必须正确使用指针?然后,如何打印存储在数组中的值?
我找到的所有示例对于初学者来说都很难理解。我阅读了有关 malloc 和 realloc 函数的信息,但我不知道该使用哪一个。
谁能帮我?谢谢!

void main() {
    int numbers[];

    do {
        allocate memory;
        add the number to new position;
    } while(user enter a number)

    for (first element to last element)
        print value;
}

【问题讨论】:

    标签: c arrays variable-length-array


    【解决方案1】:

    如果需要在运行时扩展数组,则必须动态分配内存(在堆上)。为此,您可以使用malloc 或更适合您情况的realloc

    这个页面上的一个很好的例子,我认为它描述了你想要什么。:http://www.cplusplus.com/reference/cstdlib/realloc/

    从上面的链接复制粘贴:

    /* realloc example: rememb-o-matic */
    #include <stdio.h>      /* printf, scanf, puts */
    #include <stdlib.h>     /* realloc, free, exit, NULL */
    
    int main ()
    {
      int input,n;
      int count = 0;
      int* numbers = NULL;
      int* more_numbers = NULL;
    
      do {
         printf ("Enter an integer value (0 to end): ");
         scanf ("%d", &input);
         count++;
    
         more_numbers = (int*) realloc (numbers, count * sizeof(int));
    
         if (more_numbers!=NULL) {
           numbers=more_numbers;
           numbers[count-1]=input;
         }
         else {
           free (numbers);
           puts ("Error (re)allocating memory");
           exit (1);
         }
      } while (input!=0);
    
      printf ("Numbers entered: ");
      for (n=0;n<count;n++) printf ("%d ",numbers[n]);
      free (numbers);
    
      return 0;
    }
    

    注意数组的大小是使用countvariable 记住的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多