Segmentation fault c++ with strings array
When I run my program, I get the Segmentation Fault error. I believe it is coming from how I am using the array "string *words" which is privately declared in the class definition. I use it here in the .cpp file anyone know what I need to change? heres the function I think the problem is in:
Dictionary::Dictionary(string filename){
ifstream inF;
inF.open(filename.c_str());
if (inF.fail()){
cerr << "Error opening file" <<endl;
exit(1);
}
inF >> numwords;
numwords = 3000;
words = new string(words[numwords]);
for(int i=0; i <= numwords - 1; i++){
inF >> words[i];
}
inF.开发者_运维问答close();
}
The line:
words = new string(words[numwords]);
should actually be:
words = new string[numwords];
You are going to need to learn how to use a debugger. The exact procedure depends on what system you're using. But if you run your code in a debugger, the debugger will stop on the exact line where the problem was detected. As you can imagine, this is very helpful for debugging.
Note that the line where the problem was detected and the line where the problem started may be quite different.
精彩评论