0
我的程序運行良好,直到我嘗試添加一個簡單的for循環,然後我得到一個seg故障。我會繼續併發布主體,以便您可以看到:爲循環導致隨機分段C++
using namespace std;
int main(int argc, char* argv[]){
struct question questions[argc-1]; //Array of questions to be filled by loop.
int sizeOfQuestions = argc-1; //number of questions passed in at run time
int numLines = 0; //number of lines in file
for(int i=1;i<argc;i++){ //Test loop to make sure the command line file names are read in
std::cout << argv[i] << " says hello" << std::endl;
}
for(int count=0;count<sizeOfQuestions;count++){ //This loop places the information from the files into structs
char* fileName;
std::string word = argv[count+1];
word+=".txt";
strcpy(fileName, word.c_str());
std::fstream questionFile (fileName, std::fstream::in); //Open the file
if(questionFile.good()){
cout << "In File: \t" << fileName << endl;
setQuestionFileName(&(questions[count]),word);
getline(questionFile,questions[count].programNum);
getline(questionFile,questions[count].programDesc);
getline(questionFile,questions[count].programPoints);
getline(questionFile,questions[count].programInput);
questionFile.close();
}else{
cout << "Could not open file!!!" << endl;
}
}
sort(questions,questions+sizeOfQuestions);
display(questions[0]);
cout << "" << endl;
cout << "" << endl;
display(questions[1]);
return 0;
}
將顯示它應該顯示的內容。但是,當我更改代碼的最後一節從
display(questions[0]);
cout << "" << endl;
cout << "" << endl;
display(questions[1]);
要:
for(int k=0;k<2;k++){
display(questions[k]);
cout << "" << endl;
cout << "" << endl;
}
我得到一個分段錯誤之後的第一個for循環其中說"says hello"
,這是爲什麼?即使我刪除了display(),只是在循環中做了幾個cout語句,它仍然會中斷。
那是什麼原因呢?那很簡單? – user2990286
@ user2990286是的,這是「那麼簡單」:) –
改變了一些事情,我正在工作,感謝這一點。欣賞它! – user2990286