I have looked at almost all the other Run-time Check Failure #2 problems, and only 1 has applied the error to the same location I have as in my program. The error, as commented, occurs after I end main(). I am not allocating past the end of the array, and am not changing anything after main has returned.
#include <iostream>
void findPrimes(bool primes[], const int arrSize);
int main(){
const int arrSize = 1000;
bool primes[arrSize];
for (int x = 0; x < arrSize; x++){
primes[x] = true;
}
findPrimes(primes, arrSize); //sets all non-prime numbers to false
for (int x = 0; x < arrSize; x++){ //I did not go past the size of the array.
if (primes[x]){
std::cout << x << std::endl;
}
}
return 0; //Error occurs after this point.
}
void findPrimes(bool primes[], const int arrSize){ //detects and changes non-prime numbers to false
int temp;
for (int x = 2; x < arrSize; x++){
temp = x + x;
for (int c = 0; c < arrSize; c++){
if (temp > arrSize){
break;
}
primes[temp] = false;
temp += x;
}
}
}
Your test
if (temp > arrSize){
break;
}
is on the right track to make sure you don't overrun the array bounds, but there's an off-by-one error because the index arrSize
isn't a valid array index but won't cause the loop to break
at this point. Change this to read
if (temp >= arrSize){
break;
}
and see if that fixes things.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments