Possible Duplicate:
Swapping objects using pointers
我知道如何使用指针进行交换,但是,如果我尝试这样的不同方法:
/* Pointers */
#include <stdio.h>
int main ()
{
int a=4,b=6;
swap(&a,&b);
printf("A is %d, and B is %d\n",a,b);
return 0;
}
int swap(int *a, int *b)
{
int *temp;
temp = a;
a = b;
b = temp;
return 0;
}
这是行不通的。基本上交换函数正在改变地址,比如'a'现在有'b'的地址,反之亦然。如果我打印出交换函数中的值,它会给出交换值,但它不会反射(reflect)在主要功能。谁能告诉我为什么?
因为
the swap function is changing the address, like 'a' now has the address of 'b', and vice-versa
不是真的。它不会改变他们的地址(这绝对没有任何意义)。该函数更改了指针的值 - 这些指针是地址的拷贝,并且这些指针是函数参数,因此对于函数而言是局部的。你要做的是:
int swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
return 0;
}
或者您可以使用引用(仅在 C++ 中),如下所示:
int swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
return 0;
}
并在不带 addressof 运算符的情况下调用它:
int a = 4, b = 6;
swap(a, b);
但是,如果这是针对实际实现的,而不是“编写交换函数”式的作业,那么您应该使用 std::swap()
function来自 <algorithm>
.