0

我正在学习 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;
}
4

1 回答 1

4

如果需要在运行时扩展数组,则必须动态分配内存(在堆上)。为此,您可以使用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;
}

count请注意,使用变量记住数组的大小

于 2014-03-12T16:18:33.797 回答