我在尝试运行此代码时遇到访问冲突,该代码在绑定中找到素数。
int main () {
cout << "Program initialized successfully. Please wait for the next message to appear." << endl << endl ;
int Primes[51] ;
int runner = 0 ;
int chaser = 0 ;
int bound = 0 ;
int count = 0 ;
cout << "Please enter the maximum boundary of the calculation : " ;
cin >> bound ;
cout << endl << "The number you've entered, " << bound << ", has been accepted. Please wait for the calculations." << endl ;
if (runner <= bound ) {
Primes[0] = 2;
Primes[1] = 3;
Primes[2] = 5;
Primes[3] = 7;
Primes[4] = 11;
count = 4;
for ( runner = 11 ; runner <= bound ; runner ++ ) {
while ( runner % Primes[chaser] != 0 ) {
for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) {
if ( runner % Primes[chaser] == 0 ) {
count ++ ;
Primes[count] = runner;
}
}
}
}
int chaser_count;
cout << "Here's the primes computer discovered : " << endl ;
for ( chaser_count = 0 ; chaser_count <= count ; chaser_count ++ ) {
cout << Primes[chaser_count] << endl ;
}
cout << "There is " << count << " primes discovered." << endl ;
}
return 0;
}
程序运行正常,直到计算行:if(runner&lt; = bound)
我遇到了访问冲突。
我有点知道访问违规是什么,但我不知道是什么引起了它。
编辑:
我现在得到2个答案,说我可能会有类似Primes [50]的内容,但我非常怀疑,因为我在指定绑定后立即得到错误,12。
感谢那个对此发表评论的人。
我正在使用Dev-C ++。
我找到了引发错误的地方。感谢任何评论和回答我的人。这是一个逻辑错误,我没有找到导致Prime [51]。
谢谢大家的帮助。
答案 0 :(得分:2)
这里:
for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) {
你没有用0初始化你的Primes
数组,所以循环可以反复循环,chaser可以大于51(你的Primes数组的大小)然后Primes[something_bigger_than_50]
会提升访问违规。