Я пытаюсь создать словарь с помощью С++. Словарь должен постоянно создаваться и обновляться динамически. Например, скажем, у меня есть 5 слов в моем словаре, и я хочу добавить еще одно слово, я должен создать новый словарь с местом для 6 слов, скопировать старые слова и добавить новое слово в новый словарь.
В моей функции main
я создал lexicon**
(указатель на массив указателей, поскольку каждое слово имеет указатель char
на него). Я создал функцию newStr
, чтобы получить новое слово, добавить его в словарь и отсортировать по алфавиту.
Программа запускается один раз, но когда я хочу добавить еще одно слово, я получаю предупреждение о нарушении прав доступа:
0xC0000005: место чтения нарушения прав доступа 0xDDDDDDDD.
Я не понимаю, что я делаю неправильно. Спасибо за помощь!
Вот мой код:
#define MAX 80
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
void newStr(char** lexicon, int& lexiconSize, char word[])
{
// create the new updated lexicon
char** updated = new char*[++lexiconSize];
// copy the words from the old to the updated lexicon
for (int i = 0; i < lexiconSize; i++)
{
updated[i] = new char[MAX];
if (i < lexiconSize - 1)
{
strcpy_s(updated[i], MAX, lexicon[i]);
}
// add the new word to the end of the updatedLexicon
else
{
strcpy_s(updated[i], MAX, word);
}
}
// deallocate the memory of the worlds of the old lexicon
for (int i = 0; i < lexiconSize - 1; i++)
{
delete[] lexicon[i];
}
// deallocate the memory of the old lexicon
delete[] lexicon;
// point the lexicon pointer to the updatedLexicon
lexicon = updated;
// now sort the lexicon including the new word
if (lexiconSize > 1)
{
for (int i = 1; i < lexiconSize; i++)
{
for (int j = 1; j < lexiconSize; j++)
{
if (strcmp(lexicon[j - 1], lexicon[j]) > 0)
{
char t[MAX];
strcpy_s(t, MAX, lexicon[j - 1]);
strcpy_s(lexicon[j - 1], MAX, lexicon[j]);
strcpy_s(lexicon[j], MAX, t);
}
}
}
}
// deallocate the memory created for the updated lexicon
for (int i = 0; i < lexiconSize; i++)
{
delete[] updated[i];
}
delete[] updated;
return;
}
int main()
{
int lexiconSize = 3;
char** lexicon;
char word[MAX] = {};
// initialize lexicon for testing:
lexicon = new char*[lexiconSize];
lexicon[0] = new char[MAX];
strcpy_s(lexicon[0], MAX, "maybe");
lexicon[1] = new char[MAX];
strcpy_s(lexicon[1], MAX, "this");
lexicon[2] = new char[MAX];
strcpy_s(lexicon[2], MAX, "works");
cout << "enter the word to add" << endl;
cin >> word;
newStr(lexicon, lexiconSize, word);
// menu system that allows to add/delete/print the words
// delete the lexicon at the end of the program
for (int i = 0; i < lexiconSize; i++)
{ // delete the internal words
if (lexicon[i])
{
delete[] lexicon[i];
}
}
if (lexicon)
{
delete[] lexicon;
}
return 0;
}
std::vector
. - person StoryTeller - Unslander Monica   schedule 14.01.2018std::map<std::string,std::string>
- person   schedule 14.01.2018std::map
иstd::string
внутренне используют указатели для вас. - person Christian Hackl   schedule 14.01.2018