aragon
aragon

Reputation: 114

Trouble with RAND_MAX

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

Answers (2)

Igor Pejic
Igor Pejic

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

Arjun Sreedharan
Arjun Sreedharan

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

Related Questions