Answer the question
In order to leave comments, you need to log in
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;
}
2 3 5 7 ...
78498
Process finished with exit code 0
Process finished with exit code 11
Answer the question
In order to leave comments, you need to log in
Code 11 - segmentation fault.
The array s is placed on the stack, the stack size is limited.
This is C++, so you should have a very good reason not to use std::vector in this case.
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 questionAsk a Question
731 491 924 answers to any question