Instead of bool primes[n + 1] = { 0 };
, do:
std::vector<bool> primes(n+1);
This allocates non-stack space for enough primes, and initializes them all to false
.
This version has another advantage in that the compiler may specialize it to use one bit per value, whereas your version used one byte per value.
A similar alternative that may have better performance (but is only possible when the size is known at compile-time) is
std::bitset<n+1> primes;
If you look up its documentation you may be able to improve your code's performance.