#include <iostream>
#include <string>
using namespace std;
void swap(char *&m,char *&n)
{
char *temp;
temp = m;
m = n;
n = temp;
}
int main()
{
char *x ="Hello";
char *y ="What's your name?";
swap(x,y);
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
return 0;
}
这里swap函数是利用传指针引用实现字符串交换。由于swap函数是指针引用类型,因此传入的参数是实参,而不是形参。
如果不用指针引用,那么指针交换只在swap函数作用域有效,因为在函数体中,函数栈会分配两个临时的指针变量分别指向两个指针参数,对实际没有影响。
如果不用引用,还可以用二级指针达到同样的目的。
#include <iostream>
#include <string>
using namespace std;
void swap1(char **x,char **y)
{
char *temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
char *x ="Hello";
char *y ="What's your name?";
swap(&x,&y);
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
return 0;
}