我尝试了以下代码来判断素数:
const int N = 200000;
long prime[N] = {0};
long num_prime = 0;
int is_not_prime[N]={1,1};
void Prime_sort(void)
{
for( long i = 2 ; i<N ; i++ )
{
if( !is_not_prime[i] )
{
prime[num_prime++] = i;
}
for( long j = 0; j<num_prime && i*prime[i]<N ; j++ )
{
is_not_prime[i*prime[j]] = 1;
}
}
}
但是当我运行它时,它会导致段错误! 这个错误我从来没有遇到过。我搜索了Google,它对段错误的解释如下:
A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed
但我不知道我的代码中出现这个错误的原因。请帮助我。
最佳答案
您的数组 is_not_prime
长度为 N。例如,在外部 for 循环的最后一圈,i 的值为 N-1
。当i
有那么大吗is_not_prime[i*prime[j]]
会导致你写入的内容远远超出数组范围。
我不太确定什么 j<num_prime && i*prime[i]<N
应该这样做,但这可能是错误的一部分。使用调试器单步执行程序,并查看程序崩溃时变量的值。
只需以不太复杂的方式重新编写程序,所有错误都会消失。
关于c++ - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30126079/