【问题标题】:Do not understand something about pointers [closed]不了解指针[关闭]
【发布时间】:2016-05-08 17:10:50
【问题描述】:

所以我确实已经设法解决了我的问题,但我无法理解到底是什么问题。我之前的代码是:

BinaryTree removePrivate(int x, BinaryTree *node)
{
    if ((*node).m_key < x)
        *(*node).m_right = removePrivate(x, (*node).m_right);
    else if ((*node).m_key > x)
        *(*node).m_left = removePrivate(x, (*node).m_left);
    else
        node= NULL ;
    return *node;
}

它编译得很好,但是当它被调用时,事情就变糟了。返回 *node 时访问冲突;

我已经改成:

[*]= * 已添加,[ ]= * 已删除

BinaryTree [*]removePrivate(int x, BinaryTree *node)
{
    if ((*node).m_key < x)
        [ ](*node).m_right = removePrivate(x, (*node).m_right);
    else if ((*node).m_key > x)
        [ ](*node).m_left = removePrivate(x, (*node).m_left);
    else
        node= NULL ;
    return [ ]node;
}

现在一切正常,但我真的不能 100% 确定为什么会更好。

【问题讨论】:

  • 作为对读者的一项服务,您可能想指出哪些行的不同之处。
  • 在您的旧代码中,当您的 nodeNULL 时,取消引用空指针具有未定义的行为,因为您无法取消引用任何内容。
  • 尽量使用node-&gt;m_right而不是(*node).m_right,如果可能的话why?更易读。还请在这篇文章中更正您的拼写。

标签: c++ pointers


【解决方案1】:

当您编写(*node) 时,您正在取消引用指针node。如果您使用 *(*node),就像您最初使用的那样,您将取消引用 (*node),也就是取消引用的 node。因此,您要取消引用两次,这没有意义,因为 node 因为指向 BinaryTree 对象,而不是另一个指针。

以更简单的形式:

*node = dereference node
*(*node) = dereference *node = dereference node twice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多