gpt4 book ai didi

c++ - for 循环导致随机段错误 C++

转载 作者:行者123 更新时间:2023-11-28 03:02:06 25 4
gpt4 key购买 nike

我的程序运行良好,直到我尝试添加一个简单的 for 循环然后出现段错误。我会继续发布主要内容,以便您可以看到:

     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 语句,它仍然会中断。

最佳答案

你有这些行

char* fileName;
...
strcpy(fileName, word.c_str());

但是您没有为fileName分配内存。

因为未初始化的局部变量(如 fileName)具有不确定的值,所以在没有初始化的情况下使用它们(如为指针分配内存)会导致未定义的行为

在这种情况下,您实际上不需要 fileName 指针。在 C++11 中,文件流构造函数已更改为接受 std::string(参见例如 this reference),如果您有较旧的库,则只需使用 word.c_str( ) 打开文件时。

因此,跳过 fileName 变量,直接执行

std::ifstream questionFile (word);

或者可能

std::ifstream questionFile (word.c_str());

关于c++ - for 循环导致随机段错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20511697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com