简体   繁体   中英

Increasing Size Random Number Generator Triggering Breakpoint

I'm trying to create a random number generator which increasingly outputs +1 randomly generated number(s). My problem is, after the final loop, MVS throws an exception,

"RandomGame.exe has triggered a breakpoint. occurred."

I understand this has something to do with memory positions being corrupted, which makes sense as I'm utilizing a dynamically sized array but I'm not sure how to move forward.

int size = 1;

int* array = new int[size]; 

for (int x = 0; x < 5; x++)
{
        for (int i = 0; i < size; i++)
    {
        array[i] = (rand() % 100) + 1;
        cout << array[i] << endl;
    }

        size++;
}

return 0;

I expect the program to give me 15 randomly generated numbers and then return 0. While it outputs the numbers, after it finishes, it throws the exception.

The size of array is fixed to 1 when you declared new int[size] . You increased size variable with size++ afterwards, but the size of array is not increased. std::vector is recommended if you want flexible array size.

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