【问题标题】:Unhandled exception thrown: read access violation. Tree was nullptr. If there is a handler for this exception, the program may be safely continued抛出未处理的异常:读取访问冲突。树是 nullptr。如果有这个异常的处理程序,程序可以安全地继续
【发布时间】:2016-12-15 13:46:54
【问题描述】:

我正在尝试获取树中所有整数的总和,C++,但每当我运行程序时,它总是会出现此错误:

抛出未处理的异常:读取访问冲突。树是 nullptr。如果有这个异常的处理程序,程序可以安全地继续

这是我的功能:

int sigma(Node<int> *Tree)
{
    int sum = 0;
    if (Tree->item == NULL)
    {
        return 0;
    }
    else 
    {
        sum = sum + sigma(Tree->left);
        sum = Tree->item;
        sum = sum + sigma(Tree->right);
    }
    return sum;
}

这是我的头文件:

template <typename T>
class Node
{
public:
    Node(T itm, Node *lft, Node* rht);
    Node(T itm); // for creating a leaf node 
    ~Node();
    void printTree();
    bool searchTree(T key);
    bool search(T word);
    int depth(Node *tree);
    T item;
    Node *left, *right;
};

template <typename T>
Node<T>::Node(T itm)
{
    item = itm;
    left = nullptr;
    right = nullptr;
}

template <typename T>
Node<T>::Node(T itm, Node *lft, Node *rht)
{
    left = lft;
    right = rht;
    item = itm;

}

template <typename T>
Node<T>::~Node()
{
    delete[] left, right;
}

任何人对我如何解决这个问题有任何想法吗?

【问题讨论】:

  • edit您的问题提供minimal reproducible example
  • 你已经有了答案:Tree was nullptr
  • delete[] left, right; 我从来没有见过这个(而且我永远不会使用它)。这实际上会删除所有条目吗?如果不是,它只是删除 left 而 ,- 运算符什么也不做。
  • 同样sum = Tree-&gt;item; 会覆盖sum = sum + sigma(Tree-&gt;left); 写的所有内容,只需切换行
  • 是的,当我调试它的时候就知道了!!谢谢!

标签: c++ tree sum nodes


【解决方案1】:

在开头添加检查树 == NULL

int sigma(Node<int> *Tree)
{
    int sum = 0;
    if (Tree == NULL || Tree->item == NULL)
    {
        return 0;
    }
    else 
    {
        sum = sum + sigma(Tree->left);
        sum = sum + Tree->item;
        sum = sum + sigma(Tree->right);
    }
    return sum;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2011-04-12
    • 2020-09-12
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多