[C++] 交换指针
编写一个函数,令其交换两个int指针。
交换两个值可以使用两种形式,一种是使用引用传递实参进行交换,另一种是使用指针以值传递的方式进行交换。
题目要求交换两个int指针,也可以参考交换值的两种形式。
1、使用指向指针的指针进行交换。
void swapPointerUsePointer(int **p, int **q) { int *t = *p; *p = *q; *q = t; }
2、使用引用来传递指针进行交换、
void swapPointerUseReference(int *&p, int *&q) { int *t = p; p = q; q = t; }
测试代码如下:
int main() { int a = 100, *p = &a; int b = 200, *q = &b; cout << "original pointer and value: " << endl; cout << "a: " << p << " value: " << *p << endl; cout << "b: " << q << " value: " << *q << endl; cout << endl; cout << "after swap by pointer the current pointer and value: " << endl; swapPointerUsePointer(&p, &q); cout << "a: " << p << " value: " << *p << endl; cout << "b: " << q << " value: " << *q << endl; cout << endl; cout << "after swap by reference the current pointer and value: " << endl; swapPointerUseReference(p, q); cout << "a: " << p << " value: " << *p << endl; cout << "b: " << q << " value: " << *q << endl; cout << endl; return 0; }
测试结果如下:
original pointer and value: a: 006FF780 value: 100 b: 006FF768 value: 200 after swap by pointer the current pointer and value: a: 006FF768 value: 200 b: 006FF780 value: 100 after swap by reference the current pointer and value: a: 006FF780 value: 100 b: 006FF768 value: 200