抛出异常:在Tries Implementation中写入访问冲突错误

时间:2017-12-15 04:17:34

标签: c++ visual-studio data-structures tree access-violation

我一直在尝试在Visual Studio 2017中实现Tries。 字典文件也包含精确的1000个单词,所以这不是问题。 字母表的数量也是26。 我有时会在这一行中出错

if (!temp->child[index])
“在ConsoleApplication23.exe中0x000F8922处抛出异常:0xC0000005:访问冲突读取位置0xCDCDCDFD”

或在这一行

temp->isEndOfTheWord = true; “抛出异常:写入访问冲突.temp为0xFDFDFDFD”

struct TrieNode
{

TrieNode* child[No_Of_Alphabets];
bool isEndOfTheWord;
};

class Tries
{

 public:

TrieNode* getNode()
{
    TrieNode *parent = new TrieNode;
    parent->isEndOfTheWord = false;
    for (int i = 0; i < No_Of_Alphabets; i++)
        parent->child[i] = NULL;
    return parent;
}

void insertion(TrieNode* root, string word)
{
    TrieNode *temp = new TrieNode;
    temp = root;
    for (int i = 0; i < word.length(); i++)
    {
        int index = word[i] - 'a';
        if (!temp->child[index])
            temp->child[index] = getNode();
        temp = temp->child[index];
    }
    temp->isEndOfTheWord = true;
}

bool search(TrieNode* root, string word)
{
    TrieNode *temp = new TrieNode;
    temp = root;
    for (int i = 0; i < word.length(); i++)
    {
        int index = word[i] - 'a';
        if (!temp->child[index])
            return false;
        temp = temp->child[index];
    }
    return(temp != NULL && temp->isEndOfTheWord);
}
};

void main()

{

Tries T;
TrieNode* root = new TrieNode;
root = T.getNode();

string array[1000] = {};
ifstream dict;
dict.open("Dictionary.txt");
int x = 0;
while (!dict.eof())
{
    dict >> array[x++];
}
dict.close();

for (int j = 0; j < 1000; j++)
{
    T.insertion(root, array[j]);
}

int choice = 0, z = 1;
string user_string;
cout << "TRIES IMPLEMENTATION\n\n";
while (z != 0)
{
    cout << "1-Insert A Word\n2-Search A Word\n3-Print All Words\n4-Exit\n";
    cout << "With which option would you like to proceed: ";
    cin >> choice;
    switch (choice)
    {
    case 1:
        cout << "What is the word you like to add in tries: ";
        cin >> user_string;
        T.insertion(root, user_string);
        break;
    case 2:
        cout << "What word would you like to search: ";
        cin >> user_string;
        if (T.search(root, user_string))
            cout << "Word searched found in Tries.\n";
        else
            cout << "Word searched was not found in Tries.\n";
        break;
//  case 3:
//      cout << "Printing all words:\n";

//      break;
    case 4:
        z = 0;
    }
}
system("pause");
}

0 个答案:

没有答案