iterator segmentation fault c++
我写了一个简单的算法来显示第n个素数。简而言之,它使用一个找到的素数向量来检查下一个数字是否也是素数。如果是,它将推入向量并重复直到找到第n个素数。
不幸的是,我在嵌套在while循环中的for循环中遇到分段错误,我也不知道为什么。更具体地说,该错误发生在for循环的标题中;我在for循环的主体(以及之前的主体)中添加了
该程序非常小,我不介意共享它(如果您有使用它的话),所以这是整个过程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <iostream> #include <iomanip> #include <cstring> #include <cmath> #include <vector> using std::cout; using std::cerr; using std::endl; using std::vector; int main( int argc, char* argv[] ) { if( argc != 2 ) { cerr <<"USAGE: nthPrime n" << endl; return 1; } vector< unsigned > primes; vector< unsigned >::iterator it; bool isPrime; char *sffx = ( char ) 0; unsigned n = atoi( argv[ 1 ] ), x = 3, max; primes.push_back( 2 ); while( primes.size() != n ) { isPrime = true; max = ( unsigned )sqrt( x ); for( it = primes.begin(); *it <= max; ++it ) if( !( x % *it ) ) isPrime = false; if( isPrime ) primes.push_back( x ); x += 2; } if( n == 1 ) strcpy( sffx,"st" ); else if( n == 2 ) strcpy( sffx,"nd" ); else if( n == 3 ) strcpy( sffx,"rd" ); else strcpy( sffx,"th" ); cout <<"The" << n << sffx <<" prime is" << primes.back() << endl; return 0; } |
为了方便起见,这也是makefile:
1 2 3 4 5 6 7 8 9 10 | CCFLAGS = -Wall -std=c++11 nthPrime: nthPrime.o g++ $(CCFLAGS) -o nthPrime nthPrime.o nthPrime.o: nthPrime.cpp g++ $(CCFLAGS) -c nthPrime.cpp clean: -rm *.o nthPrime |
我已经忽略了一个小时前刚写的任何评论,所以请让我知道您是否愿意。
提前致谢。
附言我已经尝试将
我可以看到一些问题:
1)使用argv而不检查
1 2 3 | unsigned n = atoi( argv[ 1 ] ), x = 3, max; |
2):
1 | char *sffx = ( char ) 0; |
不为此分配空间:
1 2 3 4 | if( n == 1 ) strcpy( sffx,"st" ); else if( n == 2 ) strcpy( sffx,"nd" ); else if( n == 3 ) strcpy( sffx,"rd" ); else strcpy( sffx,"th" ); |
好的,谢谢大家这么快就回复我! 我以为我会整天等待! 问题出在
对于可能由于类似原因而最终遇到类似问题或只是想要该程序的任何人,这里是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream> #include <iomanip> #include <cstring> #include <cmath> #include <vector> using std::cout; using std::cerr; using std::endl; using std::vector; int main( int argc, char* argv[] ) { vector< unsigned > primes; vector< unsigned >::iterator it; bool isPrime; char *sffx = new char[ 3 ]; unsigned n = atoi( argv[ 1 ] ), x = 3, max; if( argc != 2 || n < 1) { cerr <<"USAGE: nthPrime n>0" << endl; return 1; } primes.push_back( 2 ); while( primes.size() < n ) { isPrime = true; max = ( unsigned )sqrt( x ); for( it = primes.begin(); *it <= max; ++it ) if( !( x % *it ) ) isPrime = false; if( isPrime ) primes.push_back( x ); x += 2; } if( n % 10 == 1 && n % 100 != 11 ) strcpy( sffx,"st" ); else if( n % 10 == 2 && n % 100 != 12 ) strcpy( sffx,"nd" ); else if( n % 10 == 3 && n % 100 != 13 ) strcpy( sffx,"rd" ); else strcpy( sffx,"th" ); cout <<"The" << n << sffx <<" prime is" << primes.back() << endl; return 0; } |
再次享受并感谢大家!
附言 86626th prime是一个很酷的产品,我刚遇到它以高价值测试程序; 看看这个!