用交换法看待指针
我是站着看是看大佬的代码,跪着看完了代码~ 谢谢大佬Y的帮助!
下列的四个案例中,每一个Test函数对应相应的Swap函数。判断哪些Swap函数能够交换Test函数中的值。
食用方法:在main函数中调用Test函数即可。例如:我想测试第二个案例,则在main函数中调用Test02函数即可。
#include<iostream>
using namespace std;
//不能交换
void Swap01(int* a, int* b) {
int* tmp = a;
a = b;
b = tmp;
}
void Test01() {
int a = 10, b = 20;
int* p1 = &a, * p2 = &b;
Swap01(p1, p2);
cout << "a = " << a << " b = " << b << endl;
}
//能交换
void Swap02(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void Test02() {
int a = 10, b = 20;
int* p1 = &a, * p2 = &b;
Swap02(p1, p2);
cout << "a = " << a << " b = " << b << endl;
}
//部分交换
void Swap03(int** a, int** b) {
int* tmp = *a;
*a = *b;
*b = tmp;
}
void Test03() {
int a = 10, b = 20;
int* p1 = &a, * p2 = &b;
Swap03(&p1, &p2);
cout << "a = " << a << " b = " << b << endl;
cout << "*p1 = " << *p1 << " *p2 = " << *p2 << endl;
}
//能交换
void Swap04(int& a, int& b) {
int tmp = a;
a = b;
b = tmp;
}
void Test04() {
int a = 10, b = 20;
Swap04(a, b);
cout << "a = " << a << " b = " << b << endl;
}
int main() {
//Test01();
//Test02();
//Test03();
//Test04();
system("pause");
return 0;
}