I am trying to output 25 random values between 3 and 7 using a function. Every time I run my program, I receive two values that are within those parameters, but the rest are out of range.
#include <iostream>
#include <iomanip>
using namespace std;
void showArray(int a[], int size);
void showArray(int a[], const int size)
{
int i;
for (i = 0; i < size; i )
{
cout << a[i] << ", ";
}
}
int main()
{
//int iseed = time(NULL);
//srand(iseed);
srand(time(NULL));
int randomNumb = rand() % 3 4;
int array[] = {randomNumb};
showArray(array, 25);
}
This is my Output:
4, 4, -300313232, 32766, 540229437, 32767, 0, 0, 1, 0, -300312808, 32766, 0, 0, -300312761, 32766, -300312743, 32766, -300312701, 32766, -300312679, 32766, -300312658, 32766, -300312287,
CodePudding user response:
You are calling rand()
only 1 time, and storing the result in randomNumb
, which is a single integer.
Your array is being created with only 1 element in it - the value of randomNumb
. But, you are telling showArray()
that the array has 25 elements, which it doesn't. So, showArray()
is going out of bounds of the array and displaying random garbage from surrounding memory. Which is undefined behavior.
If you want 25 random numbers, then you need to allocate an array that can hold 25 numbers, and then call rand()
25 times to fill that array, eg:
#include <iostream>
using namespace std;
void showArray(int a[], const int size)
{
for (int i = 0; i < size; i)
{
cout << a[i] << ", ";
}
}
int main()
{
srand(time(NULL));
int array[25];
for(int i = 0; i < 25; i)
array[i] = rand() % 3 4;
showArray(array, 25);
}