指针实现值交换

1、一级指针实现值交换

void swap(int *v1,int *v2)

{

  int temp = 0;

  temp = *v1;

  *v1 = *v2; 

  *v2 = temp;

}

int _tmain(int argc, _TCHAR* argv[])

{

  int a = 2;

  int b = 3;

  swap(&a,&b);

  std::cout<<a<<std::endl;

  std::cout<<b<<std::endl;

  system("pause");
   return 0;

}

2、二级指针实现值交换

void swap(int **c,int **d)

{  

  int *tmp = NULL;  

    tmp = *c;

   *c = *d;

   *d = tmp;  

}

int _tmain(int argc, _TCHAR* argv[])

{

   int a,b;

   int *p1,*p2;

   a = 16;  

  b = 32;

   p1 = &a;

   p2 = &b;

   std::cout<<*p1<<std::endl;

   std::cout<<*p2<<std::endl;  

  swap(&p1,&p2);  

   std::cout<<*p1<<std::endl;

   std::cout<<*p2<<std::endl;

   system("pause");  

  return 0;

}

原文地址:https://www.cnblogs.com/jiangnanrain/p/3555035.html