假如不使用指针,函数只能对全局变量和自己的局部变量进行操作,无法操作其他函数的局部变量。
一、错误
输入3 4
输出3 4
# include <iostream>
# include<string>
using namespace std;
void swap(int x, int y) {
int temp;
temp = y;
y = x;
x = temp;
}
int main()
{
int x, y;
cin >> x >> y;
swap(x, y);
cout << x <<" " << y<<endl;
return 0;
}
二、正确
输入3 4
输出4 3
# include <iostream>
# include<string>
using namespace std;
void swap(int *x, int *y) {
int temp;
temp = *y;
*y = *x;
*x = temp;
}
int main()
{
int x, y;
cin >> x >> y;
swap(x, y);
cout << x <<" " << y<<endl;
return 0;
}