【发布时间】: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);
}
【问题讨论】:
-
提示:表达
current->next之类的内容时不要使用空格。空格使阅读时更难解析。 -
->的优先级高于*。*naya -> data等价于*(naya -> data)en.cppreference.com/w/cpp/language/operator_precedence -
同样在 C++ 中使用
nullptr优先于NULL并使用初始化列表,如Node(int x) : data(x), next(nullptr) { };
标签: c++ pointers linked-list segmentation-fault brackets