我正在学习来自 Objective-C / C 的 C++,对于一个虚拟项目,我想从/usr/share/dict/words
存储在 Mac OS X 机器上的文件中加载单词。
这个想法是加载文件并将每个单词放入一个数组中,所以我有一个array
.string
但是我在使用我的数组使用动态内存时遇到问题 - 使用new
和delete
. 我在下面添加了一些代码,如果有人可以帮忙...
所以我得到一个内存错误:
word:: A
word:: a
word:: aa
word:: aal
definitions(2758) malloc: *** error for object 0x100103b90: incorrect
checksum for freed object - object was
probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
加载词:
string* Definition::loadWords()
{
int arrayLength = 0;
arrayOfWords = new string[arrayLength];
ifstream file;
file.open("/usr/share/dict/words");
if(file.is_open())
{
while(file.good()){
string word;
getline( file, word );
this->addWord(word, arrayOfWords, &arrayLength);
}
}
file.close();
cout << endl << "There are " << arrayLength << " words" << endl;
return arrayOfWords;
};
将单词添加到数组:
void Definition::addWord(string newWord, string currentArray[], int* arrayLength)
{
cout << endl << "word:: " << newWord;
string *placeholderArray = new string[*arrayLength + 1];
placeholderArray[*arrayLength + 1] = newWord;
for(int i = 0; i < *arrayLength; i++){
placeholderArray[i] = currentArray[i];
}
(*arrayLength)++;
currentArray = placeholderArray;
delete [] placeholderArray;
}