J'apprends le C++ venant d'Objective-C/C, et pour un projet fictif je veux charger les mots du fichier /usr/share/dict/words
stocké sur des machines Mac OS X. L'idée est de charger le fichier et d'obtenir chaque mot dans un tableau, alors j'ai un array
de type string
.C++ dynamic array of string
Mais j'ai du mal à travailler correctement avec la mémoire dynamique avec mes baies - en utilisant new
et delete
. J'ai ajouté une partie du code ci-dessous, si quelqu'un pouvait aider ...
Et donc je reçois une erreur de mémoire:
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
mots de charge:
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;
};
Ajouter mots à tableau:
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;
}
Passer à l'aide de vecteurs au lieu d'utiliser la mémoire dynamique directement. –