I’m using SRand/Rand to generate an array of random numbers. The array size depends on a number the user is prompted to put in. Basically, if the user puts in a size of 9, the array should be 9 numbers. This array should then be populated using rand() with a parameter to keep the array values less than 18. The problem is, a random size array is generated sometimes. Maybe every 4th or 5th time I run the program the array might be 12-14 numbers.I can’t see the problem with my code. I’ve included a snippet below. Anyone shed some light on it?
int main(void)
{
int N;
int i;
printf("Please enter a number\n");
scanf("%d", &N);
srand (time(NULL));
int numarray[N];
for(i=1; i<numarray[N]; i++)
{
numarray[i]=rand()%21;
printf("%d\n", numarray[i]);
}
return 0;
}
You’re looping over the wrong values.
numarray[N](which is just a value in the array, and is undefined in this case since it’s one after the end of the array).I suspect you want to do this: