Word * wordList
我为这个结构分配了一些内存( ):
struct Word{
int occurrences;
std::string wrd;
};
通过写作:
Word * tempList = new Word[numWords + 1];
for(int i = 0; i < numWords; i++){
tempList[i] = wordList[i];
}
delete[] wordList;
wordList = tempList;
tempList = 0;
Word currWord = {1, wrd};
wordList[numWords] = currWord;
numWords++;
numWords
是调用这段代码之前和之后 wordList 的大小,wrd
是传递给方法的字符串。运行此代码以在wordList
.
我的问题是,当delete[]
被调用时,程序停止工作。我试着用delete
看看会发生什么,据我所知,该程序运行良好。发生了什么,为什么会delete[]
导致我的程序冻结?
wordList
是以下成员class WordsOfLength
:
class WordsOfLength{
private:
int numWords;
Word * wordList;
public:
WordsOfLength();
WordsOfLength(int nNumWords, Word* nWordList);
~WordsOfLength();
void addWord(std::string wrd);
std::string getWord(int frequency);
friend void WordData::writeWordData(const char* fileName);
friend void WordData::setWordData(const char* fileName);
};
与构造函数:
WordsOfLength::WordsOfLength(){
numWords = 0;
wordList = NULL;
}
和析构函数:
WordsOfLength::~WordsOfLength(){
delete[] wordList;
wordList = 0;
}