0

Hello Im trying to fill my array with random numbers from 1 to 50 using a pointer. When I try to do this the program crashes. This is the declaration.

populate(arraySize, numArray);

and the code

void populate(int size, int *ptr)
{
int counter = 0;
srand(unsigned(time(0)));
while (counter < size++)
{
    ptr[counter] = (rand() % 50) + 1;
    counter++;
}

}

There are no errors with the code and it runs it just crashes when this method is called

3 Answers 3

1
srand(unsigned(time(0)));
void populate(int size, int *ptr)
{
int counter = 0;

while (counter < size)
{
    ptr[counter] = (rand() % 50) + 1;
    counter++;
}

}

Remove the size++ and change it to size.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, you probably don't want to call srand in populate if you call populate more than once.
0

Another solution would be

int randomNumber () { return (std::rand()%50 +1); }

void populate(int size, int * ptr)
{
        std::srand ( unsigned ( std::time(0) ) );
        std::generate (ptr,ptr+size-1, randomNumber);
}

It is assumed that prior to call this function, user much do some range validation.

Comments

0

I guess you are trying to iterate through the array. You wrote counter < size++, which means incrementing size (I guess it's the variable that's supposed to hold the number of items) after checking for counter < size. The ++ operator does not give you another value that equals size + 1; instead, it increments size the same way size = size + 1 does. So size will increase the same time counter increases, and the index will eventually go out of bounds, and the program will crash when trying to write to that location.

Plus, as of srand, you only need to call it once (e.g. in your main()).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.