【问题标题】:Exception thrown: read access violation. **_Right_data** was 0x8. occurred抛出异常:读取访问冲突。 **_Right_data** 为 0x8。发生了
【发布时间】:2019-04-22 17:12:41
【问题描述】:

如果 addToHashTable() 函数中的条件抛出异常:抛出异常:读取访问冲突。 _Right_data 为 0x8。发生了。 hashTable 是指针类型 getNode() 返回字符串。因此,当我调用 getNode 时,它​​会返回其中存在的单词。然后我想将此单词与空字符串进行比较,以检查节点是否为空,但在这一行抛出异常。任何人请帮助我如何克服这个异常

static int const hashTableSize = 15;
Node *hashTable[hashTableSize];
.........................................................
void HashTable::addToHashTable(int hashIndex, string word)
{
    Node *node = new Node(word);
    if (hashTable[hashIndex]->getNode() == "")//exception throws at this 
    {``
        hashTable[hashIndex] = node;
    }
    else
    {
        if (hashTable[hashIndex]->getNode() != word)
        {
            node->link = hashTable[hashIndex];
            hashTable[hashIndex] = node;
        }
    }
    return;
}
.............................................
string Node::getNode()
{
    return this->word;
}
..........................................
class Node
{
public:
    Node *link;
    Node *pointNextWrongWord;
    Node();
    Node(string word);
    string getNode();
    ~Node();

private:
    string word;
    int priority;
};
................................
Main:
cout << "Type the word you want to add in Dictionary : ";
cin >> word;
hashIndex = hashTable.hashFunction(word);
hashTable.addToHashTable(hashIndex, word);

i expect this if condition compare the string returned by getNode() 
function with "" (empty string) rather than throwing exception

【问题讨论】:

    标签: c++


    【解决方案1】:

    查看您的代码,我的印象是哈希表没有分配内存。

    这段代码不正确

    if (hashTable[hashIndex]->getNode() == "")//exception throws at this 
    {
        hashTable[hashIndex] = node;
    }
    

    可能您需要一个初始化路由,将字符串单词设置为“”

    init()
       { 
          for (int i =0 ; i < sizeof(hashTable)/sizeof(hasTable[0]); ++i)
          {
              hashTable[hashIndex] = new Node("");
    
          }
       }
    

    【讨论】:

    • 我不明白这个初始化是在构造函数中完成还是什么?
    • 你有一个类型为 Node (*hashTable[hashTableSize]) 的未初始化的指针数组。在访问这个数组的任何元素之前,你应该初始化这个。在 main 开始之前从控制台读取单词,您应该调用 init 函数
    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2020-06-17
    • 2021-05-01
    相关资源
    最近更新 更多