交换两个指针的值
法一-----使用指针的引用
代码如下:
#include<iostream>
using namespace std;
//此函数用于交换指针的值(不是所指对象的值)
void swap(int *&ptr1, int *&ptr2) //参数ptr1,2先与&结合,所以本质上它是一个引用,
{
//它引用的对象类型是int *类型,所以它是一个指针的引用
int *p = ptr1;
ptr1 = ptr2;
ptr2 = p;
}
int main()
{
int val1 = 10;
int val2 = 12;
int *p1 = &val1;
int *p2 = &val2;
cout<<"交换之前: "<<endl;
cout<<"p1 = "<<p1<<" *p1 = "<<*p1<<endl;
cout<<"p2 = "<<p2<<" *p2 = "<<*p2<<endl;
swap(p1, p2);
cout<<"交换之后: "<<endl;
cout<<"p1 = "<<p1<<" *p1 = "<<*p1<<endl;
cout<<"p2 = "<<p2<<" *p2 = "<<*p2<<endl;
return 0;
}
结果如下: