voidgetMemory(int *p) { p = newint; cout <<"The pointer in getMemory() points at:" << p << endl; cout <<"The address of the pointer in getMemory():" << &p << endl; }
intmain() { int *p; getMemory(p); cout <<"The pointer in main() points at:" << p << endl; cout <<"The address of the pointer in main():" << &p << endl; delete p; return0; }
下边是代码 1 对应的程序的一个可能的输出 (具体内存地址可能不同):
1 2 3 4
The pointer in getMemory() points at: 0x10161c0 The address of the pointer in getMemory(): 0x61fdf0 The pointer in main() points at: 0x10 The address of the pointer in main(): 0x61fe18
可以看到,在 getMemory() 中的 int* 类型的指针 p 与 main() 中的 int* 类型的指针 p 并不是同一个指针(存储这两个指针的内存地址不一样,在 getMemory() 中的指针 p 存储在 0x61fdf0,而 main() 中的存储在 0x61fe18),所以虽然我们在 getMemory() 中 new 得了存储空间(getMemory() 中的指针 p 指向了 0x10161c0),但这实际上只是为 getMemory() 中的指针 p 申请了存储空间,main() 中的指针 p 并没有申请到空间(main() 中的指针 p 指向了 0x10)。
voidgetMemory2(int **p2) { *p2 = newint; cout << "The pointer in getMemory() points at:" << *p2 << endl; cout << "The address of the pointer in getMemory():" << p2 << endl; }
intmain() { int *p1; getMemory2(&p1); cout << "The pointer in main() points at:" << p1 << endl; cout << "The address of the pointer in main():" << &p1 << endl; delete p1; return0; }
下边是代码 2 对应的程序的一个可能的输出 (具体内存地址可能不同):
1 2 3 4
The pointer in getMemory() points at: 0x7461c0 The address of the pointer in getMemory(): 0x61fe18 The pointer in main() points at: 0x7461c0 The address of the pointer in main(): 0x61fe18
voidgetMemory(int *&p) { p = newint; cout << "The pointer in getMemory() points at: " << p << endl; cout << "The address of the pointer in getMemory(): " << &p << endl; }
intmain() { int *p; getMemory(p); cout << "The pointer in main() points at: " << p << endl; cout << "The address of the pointer in main(): " << &p << endl; delete p; return0; }
The pointer in getMemory() points at: 0x10261c0 The address of the pointer in getMemory(): 0x61fe18 The pointer in main() points at: 0x10261c0 The address of the pointer in main(): 0x61fe18