我有一个编程任务,要求我们使用动态分配的二维字符数组来代替字符串和向量。我有两个类:Word 包含指向 char 数组的指针,WordList 包含指向 Word 数组的指针。
分段错误来自这部分代码:
for(int i=0; i<listLength; i++)
fout << "Word " << i << (wordList[i])->getWord() << endl;
其中 fout 是 ofstream 对象,wordList 是 Word** 对象,getWord() 是 Word 对象的成员函数。问题是我在 WordList 的另一个成员函数中使用了相同的 wordList[i]->getWord() 语法并获得了正确的输出。
请让我知道是否需要更多代码来正确诊断问题
更多代码:
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include "Word.h"
using namespace std;
class WordList
{
public:
int listLength_;
Word** wordList_;
WordList()
{
char blank = ' ';
char* blankPtr = ␣
setListLength(1);
wordList_ = new Word* [listLength_];
for(int i=0; i<listLength_; i++)
{
wordList_[i] = new Word(blankPtr);
}
}
void addWord(Word* word, Word** wordList, int n)
{
Word** wl_temp = new Word* [n+1];
for(int i=0; i<n; i++)
{
wl_temp[i] = wordList[i];
}
wl_temp[n] = word;
delete[] wordList;
setWordList(wl_temp);
listLength_++;
cout << " " << (wordList_[n]->getWord()); //works here
}
void parse(const char* filename)
{
ifstream fin(filename);
char end;
char* tw;
while(fin >> end)
{
fin.unget();
fin.get(tw=new char[49], 49, ' ');
Word* w = new Word(tw);
addWord(w, getWordList(), getListLength());
delete w;
delete[] tw;
}
}
void output(const char* outfile)
{
ofstream fout(outfile);
for(int i=1; i<=listLength_; i++)
fout << "Word " << i << (wordList_[i])->getWord() << endl; //not here
fout.close();
}
};
int main(int argc, char* argv[])
{
WordList wordList;
wordList.parse(argv[1]);
wordList.output(argv[2]);
return 1;
}