Reputation: 35
I have been working on a random number gen, that creates 6 unique random numbers 1-49, i can get it working so theres 6 random numbers 1-49, or 6 unique random numbers but not all of the above at the same time. I can get the code to compile but it just crashes everytime i try and use the % 49 +1
in different spots.
Code i am using is:
{
int numbers [SIZE];
int i, j, n;
srand (time(NULL));
for (i = 0; i < SIZE; i++)
numbers[i] = i;
for(i = 0; i < SIZE; i++)
{
j = rand() % 49 + 1;
n = numbers[j];
numbers[j] = numbers[i];
numbers[i] = n;
}
for (i = 0; i < SIZE; i++)
MyOutputDebugString ("%d\n", numbers[i]);
SIZE is defined as 6.
Thanks
Upvotes: 0
Views: 321
Reputation: 127
The error is comming from calling a portion of the array that does not exist.
n = numbers[j];
The value for j is going to be your random number and most likly larger then your SIZE.
Change this part of your code:
for (i = 0; i < SIZE; i++)
numbers[i] = i;
for(i = 0; i < SIZE; i++)
{
j = rand() % 49 + 1;
n = numbers[j];
numbers[j] = numbers[i];
numbers[i] = n;
}
You can manage to pull off the same effect in one loop like this:
for (i = 0; 1 < SIZE; i++)
{
numbers[i] = rand() % 49 + 1;
}
I hope this helps.
Upvotes: 0
Reputation: 38163
SIZE is defined as 6.
So, your array numbers
is like
int numbers [6];
Once
j = rand() % 49 + 1;
is executed, j
will be between in [ 1; 49 ], so, if it's > 5, on this line, you'll have an out of range index::
n = numbers[j];
Upvotes: 5