简体   繁体   中英

Fixed size array not fixed

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;
}
for(i=1; i<numarray[N]; i++)

You're looping over the wrong values.

  • Arrays start at 0, not 1.
  • You're stopping when the index is less than the value of 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:

for(i = 0; i < N; i++)

In this line of code:

for(i=1; i<numarray[N]; i++)

numarray[N] is an uninitialized variable, so it has an unknown value. It could be zero, it could be 60,000.

The result is that your loop runs for an unknown number of iterations.

您实际上是要让for循环索引终止于numarray [N]而不是N吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM