Reputation: 114
This simple code:
int main()
{
srand(time(NULL));
const int size = rand() % RAND_MAX;
int numbers[size];
int i;
for (i = 0; i < size; i++)
numbers[i] = rand() % RAND_MAX;
for (i = 0; i < size; i++)
printf("numbers[%d]=%d\n", i, numbers[i]);
}
doesn't compile because the size of array isn't const
value.
Why does that happen?
How can I fix it?
Upvotes: 0
Views: 324
Reputation: 3698
On older compilers defining the length of an array with a variable i.e. not a constant is prohibited.
Use the malloc()
function instead:
#include <stdlib.h>
...
const int size = rand() % RAND_MAX;
int *numbers = malloc(sizeof(*numbers)*size);
Upvotes: 0
Reputation: 11453
With ANSI C89
and C90
standard, you have to know the size of the array in advance at compile time. Only in C99
is it allowed for variable sized arrays.
You can either compile it with a c99
compiler or you could allocate memory on the heap:
int *numbers = malloc(size * sizeof(int));
Upvotes: 2