#include <iostream>
using namespace std;
void test(int* p)//void test(int* &p)
{
cout<<"In the function;from main"<<endl;
cout<<"Where is the p"<<endl;
cout<<&p<<endl;
cout<<"What's the p point to"<<endl;
cout<<p<<endl;
cout<<"p=new int[10]"<<endl;
cout<<"What's the p point to now"<<endl;
p=new int[10];
cout<<p<<endl;
cout<<"And the location of p is unchanged"<<endl;
cout<<&p<<endl;
cout<<"Out of the function ;return to main"<<endl;
}
int main()
{
int *p=NULL;
cout<<"Where is the p"<<endl;
cout<<&p<<endl;
cout<<"What's the p point to"<<endl;
cout<<p<<endl;
test(p);
cout<<"What's the p point to now"<<endl;
cout<<p<<endl;
return 0;
}
Where is the p
0012FF28
What's the p point to
00000000
In the function;from main
Where is the p
0012FE54
What's the p point to
00000000
p=new int[10]
What's the p point to now
001E1AD0
And the location of p is unchanged
0012FE54
Out of the function ;return to main
What's the p point to now
00000000
请按任意键继续. . .
小结:
指针归根到底也是一个值,存放在栈中,有他自己的位置,他的值是指向内存的地址的。
就像这段代码,函数test的形参一开始指向的内存地址是main函数中p指向的地址。
至此,main函数中的p在test函数中没什么作用了,而test函数的作用仅仅是为形参p开辟空间,造成内存泄露。