我正在学习C++并试图解决编程挑战中的问题。我一直在解决跳投问题。为了说明问题,我的程序运行了,但在输入第一行并得到输出后,出现了分段错误。这里是我的代码:获取分段错误错误C++
#include <iostream>
#include <cmath>
using namespace std;
bool is_jolly(int *list, int cap, bool* container){
int difference = 0;
for(int i=0; i<cap-1; i++){
difference = list[i] - list[i+1];
if(abs(difference) < cap && abs(difference) >= 1 && container[difference] == false){
container[difference] = true;
continue;
}
else return false;
}
return true;
}
int main(){
int n;
bool used[30001];
while(cin >> n){
int * num_list = new int[n];
for(int i=0; i<n; i++){
cin >> num_list[i];
used[i+1] = false;
}
if(is_jolly(num_list,n,used))
cout << "Jolly" << endl;
else cout << "Not Jolly" << endl;
delete[] num_list;
}
return 0;
}
你是否尝试用调试器进入你的代码? – taocp 2014-08-27 18:39:39
开始使用'std :: vector'而不是原始数组,你会看到所有的seg错误消失! – CoryKramer 2014-08-27 18:40:07
您应该阅读Eric Lippert撰写的[本博客文章](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/),了解如何调试小程序,如应用程序和应用程序那里描述的技术。 – 2014-08-27 18:40:08