Search code examples
carraysvariable-length-array

How to expand a one-dimensional array at runtime in C?


I'm learning C language and I have a question about dynamic memory allocation.
Consider that I have a program that the user must enter numbers or typing the letter "E" to exit the program. The numbers that the user enter must be stored in a one-dimensional array. This array begins with a single position.
How can I do to increase my array of integers to each number that the user enters to store this number in this new position? I think I must use pointers correct? And then, how do I print the values ​​stored in the array?
All the examples I find are complex to understand for a beginner. I read about the malloc and realloc functions but I don't know exactly which one to use.
Can anyone help me? Thanks!

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;
}

Solution

  • If you need to expand an array at runtime, you must allocate memory dynamically (on the heap). To do so, you can use malloc or more suitable for your situation, realloc.

    A good example on this page here, which I think describes what you want.: http://www.cplusplus.com/reference/cstdlib/realloc/

    Copy pasted from the link above:

    /* 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;
    }
    

    Note that the size of the array is remembered using countvariable