Random 500,000 numbers and assign to array

Hi guys, basically i try to random numbers and assign it to array
1
2
3
4
5
6
7
8
int array[];

cin >> size;

for (int i = 0; i < size; i++)
{
    array[i] = rand % 1000000;
}


but when i try to run and input the size to be big number, it just stop running.
please help me
Last edited on
Your code has 2 mistakes.
First on line 1 you don't give your array a size.
Second on line 7 you don't use () for the function call.
The code you've shown doesn't make any sense. int array[]; is not legal since there is no size for a. If you meant to say int array[size]; and put it after you've read in the size, then if you enter too large a size it will overflow the stack. But 500000 4-byte integers is only 2 megabytes, so that's a little small to overflow the stack. Maybe you accidentally typed in 5000000 instead, since 20 megabytes is probably enough. In either case, it's not sensible to put such a large structure on the stack, and variable length arrays are not standard C++ anyway. You should use a vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <random>
#include <vector>

int main() {
    std::default_random_engine rng(std::random_device{}());
    std::uniform_int_distribution<> dis(0,999999);

    std::cout << "Size: ";
    int size;
    std::cin >> size;

    std::vector<int> v(size);

    for (int i = 0; i < size; i++)
        v[i] = dis(rng);
}

Topic archived. No new replies allowed.