c - Random array size at the beginning? -
i want make random sized array everytime program executes @ first compiler yells me
"error 2 error c2466: cannot allocate array of constant size 0"
is there way can randomly choose size
size = rand() % 100
@ beginning , intialize array int myarray[size]={0}
??? or should everytime initialize exact number @ beginning?
int main(void) { int i; int size=rand()%100; int array2[size]={0}; for(i=0;i<size;i++) //fill array random numbers array2[i]=rand()%100; ... }
you can use malloc()
or calloc()
in c. example,
int size=(rand()%100)+1; // size can in range [1 100] int *array2 = (int*) malloc(sizeof(int)*size);
but @ same time, array size can not other constant value.
the following 2 declarations valid.
int a[10];
and
#define max 10 int b[max];
but error if try declare using following methods.
int x=10; int a[x];
and
const int y=10; int b[y];
Comments
Post a Comment