C++中指针打印输出不同内存地址的原因是什么
C++二级指针打印输出逻辑说明
所有疑问的核心前提:指针本身也是变量。只要是变量,就会在内存中占据独立的存储空间,有属于自己的内存地址;而指针变量中存储的内容,是它指向的目标对象的内存地址,这两个地址不要混淆。
测试代码
#include <iostream> using namespace std; class Node { }; int main() { Node *head = NULL; Node *second = NULL; Node *tail = NULL; head = new Node(); second = new Node(); tail = new Node(); Node** node_ref = &head; cout << head << endl; //memory address of head cout << &head << endl; //prints an address different than the line above? Why? cout << node_ref << endl; //prints the same as cout << &head; cout << &node_ref << endl; //prints new address (Is this the address of the new pointer?) cout << *node_ref << endl; //prints the same as cout << head; Why? return 0; }
逐行输出逻辑解释
cout << head << endl;
原注释表述有误:这行打印的不是head本身的地址,是一级指针head中存储的数值——也就是new Node()在堆上分配的Node实例的内存地址。cout << &head << endl;
和上一行输出不同是完全正常的:&是取地址符,这里取的是指针变量head自身在栈上的存储地址。head是main函数的局部变量,分配在栈区,它自己占一块栈内存,这块内存的地址和它存储的堆对象地址没有关联,自然不一样。cout << node_ref << endl;node_ref是Node**类型的二级指针,定义时初始化为&head,也就是它存储的数值就是head变量的栈地址,所以输出和&head完全一致。cout << &node_ref << endl;
你的猜测是对的:这里取的是二级指针变量node_ref自身的栈内存地址。node_ref同样是main函数的局部变量,在栈上有独立的存储空间,所以会输出新的、不重复的地址。cout << *node_ref << endl;*是解引用运算符,对二级指针node_ref解引用,得到的是它指向的目标——也就是head这个一级指针本身。打印一级指针head输出的就是它存储的堆对象地址,所以和第一行cout << head的结果完全相同。
内存指向链路梳理
栈区(函数局部变量存储区) → 堆区(动态分配内存存储区)
- 栈上的
node_ref变量:自身地址为&node_ref,存储内容为head变量的栈地址- 栈上的
head变量:自身地址为&head(即node_ref存储的内容),存储内容为堆上Node实例的地址- 堆上的Node实例:地址为
head存储的内容(即*node_ref)
内容的提问来源于stack exchange,提问作者the_martian
相关产品推荐
相关产品推荐

