#include<iostream>
using namespace std;
void test(int *b) //相当于把a的地址复制了一份给b
{
cout<<"函数中b= "<<b<<endl;
*b=10;
b=NULL;
}
void test1(int *&b) //相当于为int *类型的共享变量,b和a共享指针
{
*b=10;
b=NULL;
}
int main()
{
int *a=(int *)malloc(sizeof(int));
*a=15;
cout<<"修改前a= "<<a<<endl;
cout<<"修改前*a= "<<*a<<endl;
test(a);
cout<<"修改后a= "<<a<<endl;
cout<<"修改后*a= "<<*a<<endl;
test1(a);
cout<<"修改后a= "<<a<<endl;
cout<<"修改后*a= "<<*a<<endl;
}
运行结果:
由结果可以得知:
①.test函数中指针变量b复制了一份a的地址,修改b的指针对a没有影响。由于指针b指向a所在的同一块内存单元,因此test函数中改变*b的值,也会改变*a的值。
②.test1函数中因为引用符号&的存在,致使a,b共享同一指针与内存单元,修改b的指针会对a也产生影响。
分析完毕,欢迎评论区提问以及补充。