我正在尝试使用C++构建一个字典。必须始终动态地创建和更新字典。例如,假设我在我的字典里有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;
}发布于 2018-01-14 10:33:22
您的问题是lexicon是通过值传递给newStr()的。
因此,赋值lexicon = updated对调用方不可见。
由于该函数释放lexicon[i]引用的所有动态分配内存,因此lexicon在main()中的所有后续使用都有未定义的行为。
顺便说一句,在newStr()内部分配的所有内存都是泄漏的--在函数返回后没有变量引用它,因此不能在代码中释放它。
不要直接使用指针和操作符new,而是查找标准容器(std::vector)和std::string (用于管理字符串数据)。
发布于 2018-01-14 10:30:11
https://stackoverflow.com/questions/48248614
复制相似问题