我正在学习从 Objective-C/C 过来的 C++,对于一个虚拟项目,我想从存储在 Mac OS X 上的 /usr/share/dict/words
文件中加载单词机器。
我的想法是加载文件并将每个单词放入一个数组中,所以我有一个 string
类型的 array
。
但是我在使用我的数组使用动态内存时遇到了问题 - 使用 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;
}
最佳答案
我首先看到的是:
placeholderArray[*arrayLength + 1] = newWord;
您正在向数组末尾添加一个元素。数组从 0 开始索引。例如,如果数组长度为 5,则数组中的最后一个元素位于索引 4 处。因此该行应为:
placeholderArray[*arrayLength] = newWord;
然后你将删除你的数组:
currentArray = placeholderArray;
delete [] placeholderArray;
因为您只是将 currentArray 设置为指向 placeholderArray,然后将其删除。
同样通过引用传递比通过指针传递要好得多。所以与其这样:
void Definition::addWord(string newWord, string currentArray[], int* arrayLength)
使用这个:
void Definition::addWord(string newWord, string currentArray[], int& arrayLength)
您不必每次都使用 * 来获取值。
这里有一个使用引用的教程: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
还可以节省您自己的时间和精力,尽早学习使用 vector 和 STL 容器而不是数组。
这是使用 vector 的教程: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm
关于C++动态字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14948919/