补充swap的形参
#include
using namespace std;
void swap(
// 在此处补充你的代码
)
{
int * tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 3,b = 5;
int * pa = & a;
int * pb = & b;
swap(pa,pb);
cout << pa << "," << * pb;
return 0;
}***
void swap(int** a, int**b
// 在此处补充你的代码
)
#include
using namespace std;
void swap(int *a,int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int main()
{
int a = 3,b = 5;
int * pa = & a;
int * pb = & b;
swap(pa,pb);
cout << "a:"<<a << "," << "b:"<<b;
return 0;
}
输出:
a:5,b:3
楼主是想通过函数交换a和b的值吗?
首先,你应该知道的是传入函数中的是一个副本。也就是说我们为了改变a本身,传入了a指针的副本,通过指针找到a存在的地方,真正的改变a的数值。
或许下面这个简单的例子更好理解一些。
#include
using namespace std;
void setValue(int a)
{
a = 10;
}
void setValuebyPoint(int *a)
{
*a = 9;
}
int main()
{
int a = 8;
cout<<a<<endl;
setValue(a);
cout<<"setValue:"<<a<<endl;
setValuebyPoint(&a);
cout<<"setValuebyPoint:"<<a<<endl;
}
输出:8
setValue:8
setValuebyPoint:9
这道题主要是考察C++中的 引用这个知识点的应用。
正确答案应该是:
void swap(int &a, int &b)// 在此处补充你的代码
{
int * tmp = a;
a = b;
b = tmp;
}