-1

I want to make a random sized array everytime program executes at first but compiler yells me

"Error  2   error C2466: cannot allocate an array of constant size 0"

Is there any way that I can randomly choose the SIZE by SIZE = rand() % 100 at the beginning and then intialize the array with int myarray[SIZE]={0} ??? or should I everytime initialize it with an exact number at the beginning?

int main(void) {
    int i;
    int SIZE=rand()%100;
    int array2[SIZE]={0};

    for(i=0;i<SIZE;i++)     //fill the array with random numbers
        array2[i]=rand()%100;
    ...
}
Lyrk
  • 1,936
  • 4
  • 26
  • 48

4 Answers4

2

You indicated you're using Microsoft's visual studio. MS visual studio is not c99 compilant (they cherry pick at best) and one of the missing features is VLAs.

The best you'll be able to do with MS VS is to do this dynamically using malloc():

int main(int argc, char *argv[])
{
    int i;
    int SIZE=rand()%100;
    int *array2=malloc(SIZE * sizeof(int));  // allocate space for SIZE ints

    for(i=0;i<SIZE;i++)     //fill the array with random numbers
        array2[i]=rand()%100;
    free(array2);   // free that memory when you're done.
    return 0;
}

If you want to switch compilers, there are other options.

Mike
  • 47,263
  • 29
  • 113
  • 177
1

Note that rand()%100 can and will be 0. If you want a random value 1 <= n <= 100 then you need to use (rand()%100)+1

K Scott Piel
  • 4,320
  • 14
  • 19
1

You can use malloc() or calloc() to do this in C. For example,

int SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
int *array2 = (int*) malloc(sizeof(int)*SIZE);

But at the same time, the array size can not be anything other than a constant value.

The following two declarations are valid.

int a[10];

and

#define MAX 10
int b[MAX];

But you will get an error if you try to declare using the following methods.

int x=10;
int a[x];

and

const int y=10;
int b[y];
Deepu
  • 7,592
  • 4
  • 25
  • 47
  • One note for this solution: [In C, don't typecast the return from malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) – Mike May 02 '13 at 18:24
1

The best way to do this would be to make your array a pointer and use malloc:

int SIZE=(rand()%100) + 1; //range 1 - 100
int *array2 = malloc(sizeof(int) * SIZE);

Afterwards you can use array2 much as you would use an array.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
  • One note for this solution: [In C, don't typecast the return from malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) – Mike May 02 '13 at 18:24