指针引用如何在 C++ 中工作?
How pointer reference works in C++?
我有 3 个建议:
Node* head;
Node* temp=head;
Node* p=new Node(2);
现在我分配:
temp->next=p
下一个head也会换吗?
head->next=?
是的,如果 head
实际上指向一些分配的内存,temp
将指向相同的内存。
示例:
#include <iostream>
struct Node {
Node(int X) : x(X) {}
int x;
Node* next;
};
int main() {
Node* head = new Node(1);
Node* temp = head; // temp points to the same memory as head
Node* p = new Node(2);
temp->next = p; // head->next is the same as temp->next
std::cout << head->next->x << '\n' // prints 2
delete head;
delete p;
}
我有 3 个建议:
Node* head;
Node* temp=head;
Node* p=new Node(2);
现在我分配:
temp->next=p
下一个head也会换吗?
head->next=?
是的,如果 head
实际上指向一些分配的内存,temp
将指向相同的内存。
示例:
#include <iostream>
struct Node {
Node(int X) : x(X) {}
int x;
Node* next;
};
int main() {
Node* head = new Node(1);
Node* temp = head; // temp points to the same memory as head
Node* p = new Node(2);
temp->next = p; // head->next is the same as temp->next
std::cout << head->next->x << '\n' // prints 2
delete head;
delete p;
}