引用交换两个变量的值【C++】

(1)
void change(int x,int y)
{
 int temp;
 temp=x;
 x=y;
 y=temp;
 
}
 
int _tmain(int argc, _TCHAR* argv[])
{
 int x=10,y=20;
 cout<<"交换前"<<x<<y<<endl;
 change(x,y);
 cout<<"交换后"<<x<<y<<endl;
 system("pause");
 return 0;
}
这种方法并不能实现变量值的交换,当change函数被调用时,系统首先创建两个临时变量x和y,这两个临时变量的名字虽然和main函数中的相同,但是和他们没有关系,存储于不同的区域,属于change函数的局部变量。使用change函数时调换的只是零时变量的值,而main函数中的x,y 并没有变化。
(2)

void change(int *x,int *y)
{
 int temp;
 temp=*x;
 *x=*y;
 *y=temp;
 
}
 
int _tmain(int argc, _TCHAR* argv[])
{
 int x=10,y=20;
 cout<<"交换前"<<x<<y<<endl;
 change(&x,&y);
 cout<<"交换后"<<x<<y<<endl;
 system("pause");
 return 0;
}

定义两个指针型变量,取实参的地址给x,y ,注意的是参数 的地址是唯一的,所以指针指向的数据内存单元也是唯一的,而指针交换了数据内存单元里面的数据。
 
发布了36 篇原创文章 · 获赞 17 · 访问量 6274

猜你喜欢

转载自blog.csdn.net/qq_39248307/article/details/77963663