Sheldon Sheldon - 4 months ago 9
C Question

Is creating array with a variable number of elements possible?

Whenever I need to create an array with a number of elements not known until execution time I do this.

int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int myArray[n];
for(i = 0; i < n; i++)
myArray[i] = 0;


However I've been told by 3 people with a PhD in Computer Science not to do it, because "it's not guaranteed to work on every compiler", and that the number of the elements in an array must be known at compile-time. So they do that like this.

int myArray[1000];
int n, i;
printf("Number of elements: ");
scanf("%d, &n);
//we must stop at the n element
for(i = 0; i < n; i++)
myArray[i] = 0;


Which one should I use? When it's not guaranteed to work? Is it just a memory waste or a need to maintain legacy?

Answer

"it's not guaranteed to work on every compiler"

Yes, basically, correct.

The first approach, VLA, variable length array, was a part of C99 standard. However,

  • in C11, that has been made optional. You better not rely on that feature.
  • C89 did not have that as a port of the standard. gcc extensions were there, however, to support them.

Quoting C11, chapter ยง6.7.6.2/p5

[....] If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)

As an alternative approach, you can always use a pointer and dynamic memory allocation like malloc() and family, if you have to rely on run-time values.

Taken together, to answer the question

Is creating array with a variable number of elements possible?

It is possible, but only with VLA support. Without that, you have to sate yourself with a pointer and memory allocation functions, at best.

Comments