Created
October 25, 2012 15:33
-
-
Save mike-zhang/3953398 to your computer and use it in GitHub Desktop.
交换两个指针(c++)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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