指向指针的指针,交换指针的值
程序员文章站
2024-01-01 17:08:10
...
交换指针的值
法二—通过二级指针实现
代码如下:
#include<iostream>
using namespace std;
//此函数用于交换指针的值,通过二级指针实现
void swap(int **ptr1, int **ptr2)//ptr先于左边第一个*结合成为一个指针
{ //再看它指向的对象是类型是int *类型即指针,所以它是一个指向指针的指针。
int *temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
int main()
{
int val1 = 3;
int val2 = 4;
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;
}
结果如下: