我正在研究链表并尝试理解指针,他们自己的物理地址和他们指向的地址。我编写用于打印列表的代码,并发现一个奇怪的现象,就像标题描述的那样。这是代码:
#include <iostream>
using namespace std;
struct Node {
int num;
struct Node *next;
};
void addNode(Node*&, int);
void printList(Node*);
int main() {
Node *a = NULL;
addNode(a, 1);
addNode(a, 2);
addNode(a, 3);
cout << "After adding three nodes, a contains " << a << ", a locates at " << &a << endl;
cout << "a->next contains " << a->next << endl;
cout << "a->num = " << a->num << endl;
cout << endl;
printList(a);
cout << "After printing, a contains " << a << ", a locates at " << &a << endl;
cout << "a->next contains " << a->next << endl;
cout << "a->num = " << a->num << endl;
cout << endl;
}
void addNode(Node *&A, int i) {
Node *temp;
temp = new Node;
temp->num = i;
temp->next = A;
A = temp;
}
void printList(Node *A) {
cout << "1. printList: A contains " << A << ", A locates at " << &A << endl;
cout << endl;
Node *current;
cout << "2. current contains " << current << " (uninitialized), current locates at " << ¤t << endl;
//cout << current->next << endl;
cout << endl;
current = A;
cout << "3. After being assigned by A, current contains " << current << ", current locates at " << ¤t << endl;
cout << endl;
while(true) {
if(current == NULL) break;
cout << "num is " << current->num << endl;
current = current->next;
cout << "After being assigned by next, current contains " << current << ", current locates at " << ¤t << endl;
cout << endl;
}
cout << "End of the list" << endl;
cout << endl;
}
结果如下:
添加三个节点后,a包含0x2822a98,a位于0x6bfebc a->接下来包含0x2822a88 a-> num = 3
printList:A包含0x2822a98,A位于0x6bfea0
当前包含0x6bfebc(未初始化),当前位于0x6bfe8c
- 醇>
在被A分配后,当前包含0x2822a98,当前位于0x6bfe8c
num是3在被next分配后,current包含0x2822a88, current位于0x6bfe8c
num是2在被next分配后,current包含0x2822a78, current位于0x6bfe8c
num为1在被next分配后,current包含0,current 位于0x6bfe8c
列表的结尾
打印后,a包含0x2822a98,位于0x6bfebc a-&gt; next 包含0x2822a88 a-> num = 3
注意,第2项:current包含0x6bfebc。 “0x6bfebc”与地址相同,地址显示在第一行。但我认为未初始化的指针变量应指向随机地址。为避免重合,我尝试重新打开程序并重新启动计算机,但每次只是锁定到a的地址。有人可以解释一下里面到底发生了什么。感谢。
为了更具可读性,我在最后添加了一个截图。希望它有所帮助。