Reputation:
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?
Upvotes: 1
Views: 2405
Reputation: 134286
"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,
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.
Upvotes: 2
Reputation: 223689
If you want something that is C89 compliant and doesn't use too much memory, there is a third option which is to allocate memory dynamically:
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int *myArray = malloc(sizeof(int)*n); // allocate space for n ints
if (myArray == NULL) {
perror("malloc failed");
exit(1);
}
for(i = 0; i < n; i++)
myArray[i] = 0;
Just be sure to call free
on the allocated memory when you're done with it.
Upvotes: 1