交换两个指针
在博客园看到这片文章: http://www.cnblogs.com/MikeZhang/archive/2012/10/26/swapPtr20121026.html 的标题,就想自己实现下
任务就是将两个指针进行交换,自己也实现了一下,记录一下,如果要看解释,还是去原帖吧。
第一种方法就是用二级指针,第二种方法就是用 指针引用。代码如下:
#include "stdafx.h" #include <iostream> using namespace std; void swap_point1(int **p1, int **p2) { int* temp = *p1; *p1 = *p2; *p2 = temp; } void swap_point2(int*&p1, int *&p2) { int* temp = p1; p1 = p2; p2 = temp; } int main() { int a = 10, b = 20; int *p1 = &a; int *p2 = &b; cout<<"a="<<a<<", b="<<b<<endl; cout<<"p1="<<p1<<",p2="<<p2<<endl; cout<<"*p1="<<*p1<<",*p2="<<*p2<<endl; //swap_point1(&p1,&p2); swap_point2(p1,p2); cout<<"-----------------------------------------"<<endl; cout<<"a="<<a<<", b="<<b<<endl; cout<<"p1="<<p1<<",p2="<<p2<<endl; cout<<"*p1="<<*p1<<",*p2="<<*p2<<endl; }