A
A
avion2018-10-10 18:43:42
C++ / C#
avion, 2018-10-10 18:43:42

Array size in C++?

The code uses the Sieve of Eratosthenes (with the argument n <= 1.000.000 everything works fine:

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

void fff(int n) {

    int s[n+1], j = 0;

    s[1] = 0;

    for (int i = 2; i <= n; i++) {
        s[i] = 1;
    }

    for (int i = 2; i * i <= n; i++) {
        if (s[i] == 1) {
            for (int l = i * i; l <= n; l += i) {
                s[l] = 0;
            }
        }
    }

    for (int i = 2; i <= n; i++) {
        if (s[i] == 1) {
        cout << i << " ";
        j++;
        }
    }

    cout << endl;
    cout << j;
}

int main() {
    fff(1000000);

    return 0;
}

Program output:
2 3 5 7 ...
78498
Process finished with exit code 0

But for n >= 10.000.000 the program doesn't output anything except:
Process finished with exit code 11
What's the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2018-10-10
@avion123678

Code 11 - segmentation fault.
The array s is placed on the stack, the stack size is limited.

V
Vitaly, 2018-10-10
@vt4a2h

This is C++, so you should have a very good reason not to use std::vector in this case.

V
Vasily Melnikov, 2018-10-11
@BacCM

Nobody wrote what to do. Although it's obvious, I'll put in my 3 cents.
You can use new[], std::array, or std::vector, or reconfigure the system for a larger stack

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question