Can you define the size of an array at runtime in C

rhr picture rhr · Oct 20, 2009 · Viewed 28.6k times · Source

New to C, thanks a lot for help.

Is it possible to define an array in C without either specifying its size or initializing it.

For example, can I prompt a user to enter numbers and store them in an int array ? I won't know how many numbers they will enter beforehand.

The only way I can think of now is to define a max size, which is not an ideal solution...

Answer

BobbyShaftoe picture BobbyShaftoe · Oct 20, 2009

Well, you can dynamically allocate the size:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int *array;
  int cnt;
  int i;

  /* In the real world, you should do a lot more error checking than this */
  printf("enter the amount\n");
  scanf("%d", &cnt);

  array = malloc(cnt * sizeof(int));

  /* do stuff with it */
  for(i=0; i < cnt; i++)
    array[i] = 10*i;

  for(i=0; i < cnt; i++)
    printf("array[%d] = %d\n", i, array[i]);

  free(array);

  return 0;
}