【问题标题】:What is the significance of using a bracket on the node of the linked list in c++?c++中链表的节点上使用方括号有什么意义?
【发布时间】:2020-06-02 22:01:37
【问题描述】:

在下面的代码中,mn 函数中有一个节点指针naya。在if 条件下,naya 指针第一次指向空值,我们正试图访问它的数据。如果我们尝试在没有naya 指针周围的括号的情况下执行相同的代码,则会出现如下错误:

prog.cpp: In function ‘void mn(Node*, Node**)’:
prog.cpp:66:50: error: request for member ‘data’ in ‘* naya’, which is of pointer type ‘Node*’ (maybe you meant to use ‘->’ ?)
     if(*naya == NULL || temp -> data <= *naya -> data)
                                             ^*

但是当我们使用方括号时,它的工作正常。为什么?

下面是整个代码:

#include <bits/stdc++.h>
using namespace std;
class Node {
 public:
  int data;
  Node* next = NULL;
  Node(int x) {
    data = x;
    next = NULL;
  }
};

void mn(Node* temp, Node** naya) {
  Node* current;

  if (*naya == NULL || temp->data <= (*naya)->data) {
    temp->next = *naya;
    *naya = temp;
  } else {
    current = *naya;
    while (current->next != NULL && (current->next->data < temp->data)) {
      current = current->next;
    }
    temp->next = current->next;
    current->next = temp;
  }
}
Node* isort(Node* head) {
  Node* temp = head;
  Node* naya = NULL;
  while (temp != NULL) {
    Node* nex1 = temp->next;
    mn(temp, &naya);
    temp = nex1;
  }
  return naya;
}
void printll(Node* head) {
  Node* temp = head;
  while (temp != NULL) {
    cout << temp->data;
    temp = temp->next;
  }
}
int main() {
  Node *head = NULL, *temp = NULL;
  int a;
  cin >> a;
  for (int i = 0; i < a; i++) {
    int x;
    cin >> x;
    Node* newnode = new Node(x);
    if (head == NULL) {
      head = newnode;
      temp = head;
    } else {
      temp->next = newnode;
      temp = temp->next;
    }
  }
  head = isort(head);
  printll(head);
}

【问题讨论】:

标签: c++ pointers linked-list segmentation-fault brackets


【解决方案1】:

之所以必须这样写是因为operator precedence,它决定了使用哪些操作数来执行哪些操作。您可以从该链接中看到“成员访问”或-&gt; 默认绑定在“间接(取消引用)”或*a 之前。通过将取消引用操作括在括号中,您可以指定您希望它在成员访问之前首先被绑定。

为了使这一点更具体,在您的示例中,naya 是一个指向指针的指针。默认情况下,C++ 尝试首先绑定成员访问操作的操作数(即naya-&gt;data)。如果我们要在此处添加括号以明确顺序,它将如下所示:

*(naya->data)

这具有取消引用naya 的效果,然后在取消引用的对象中查找data 成员变量。取消引用的对象是指针,所以它没有data 成员。如果它没有出错,它将继续尝试取消引用数据成员的值(表达式的 * 部分)。

当您输入(*naya)-&gt;data 时,您是在告诉C++ 它应该取消引用naya*,而不是默认情况下的(naya-&gt;data)(*naya) 是指向 Node 对象的指针,所以 -&gt; 会成功找到数据成员。

【讨论】:

  • “运算符优先级”表示操作数与运算符的关联方式;不是评价顺序。这是一个常见的误解,例如在f() + g() * h() 中,* 具有更高的优先级,但f() 可能在其他人之前被评估。
  • 感谢@MM 的澄清!我会更新答案。
猜你喜欢
  • 1970-01-01
  • 2013-04-23
  • 2023-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 2013-06-15
  • 2012-12-16
相关资源
最近更新 更多