Skip to content

Instantly share code, notes, and snippets.

@mike-zhang
Created October 25, 2012 15:33
Show Gist options
  • Save mike-zhang/3953398 to your computer and use it in GitHub Desktop.
Save mike-zhang/3953398 to your computer and use it in GitHub Desktop.
交换两个指针(c++)
#include <iostream>
using namespace std;
//using pointer
void ptrSwap1(int **pa,int **pb)
{
int *ptmp = *pa;
*pa = *pb;
*pb = ptmp;
}
//using reference
void ptrSwap2(int *&pa,int *&pb)
{
int *pk = pa;
pa = pb;
pb = pk;
}
int main()
{
for(int i=1; i<=3; ++i)
{
int a=56,b=78;
int *pa=&a,*pb=&b;
cout<<"a : "<<a<<"\tb : "<<b<<endl;
cout<<"*pa : "<<*pa<<"\t*pb : "<<*pb<<endl;
cout<<"pa : "<<pa<<"\tpb : "<<pb<<endl;
switch(i)
{
case 1:
//using pointer
ptrSwap1(&pa,&pb);
break;
case 2:
//using reference
ptrSwap2(pa,pb);
break;
default:
//using std::swap
swap(pa,pb);
break;
}
cout<<"a : "<<a<<"\tb : "<<b<<endl;
cout<<"*pa : "<<*pa<<"\t*pb : "<<*pb<<endl;
cout<<"pa : "<<pa<<"\tpb : "<<pb<<endl<<endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment