【问题标题】:Why parenthesis are needed when dereferencing a double pointer?为什么取消引用双指针时需要括号?
【发布时间】:2020-05-12 05:11:57
【问题描述】:

我有这个功能可以删除单个链表中的第一个节点:

void removeFront(Node **tmpHead){       
if ((*tmpHead)->next == NULL)
    cout << "Single Node! RemoveFront() aborted!\n";'
else{
Node *oldNode = *tmpHead;
*tmpHead = oldNode->next;
delete oldNode;     
}

}

为什么我需要在 if 语句中将 *tmpHead 放在括号内?如果我不这样做,则会给出编译错误。

【问题讨论】:

  • 可以这样想显示错误。
  • 因为它是Node **,而不是Node *
  • 这里的if 让人分心。每当您需要查看或更改 Node 的内容时,都会出现同样的问题。

标签: c++ pointers dereference


【解决方案1】:

由于operator precedence*tmpHead-&gt;next 被解释为*(tmpHead-&gt;next)

由于tmpHeadNode** 类型,tmpHead-&gt;next 不是有效的子表达式。

这就是为什么您需要在*tmpHead 周围使用括号并使用(*tmpHead)-&gt;next == NULL

【讨论】:

    猜你喜欢
    • 2017-06-07
    • 2013-04-01
    • 2021-06-06
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多