引用为参数实现两个字符串变量的交换

来源:互联网 发布:知乎 扑克投资家 编辑:程序博客网 时间:2024/06/07 11:10

如题所示,通过调用传递引用的参数,实现两个字符串变量的交换,例如:

char * ap="hello";

char * bp="how are you";

交换的结果使得ap和bp指向的内容分别为:

char * ap="how are you"; ="hello";

char * bp="hello";

好的,下面开始代码:

#include <iostream.h>

void swapstring(char * & ca,char * & cb)
{
 char * temp;
 temp=ca;
 ca=cb;
 cb=temp;
}

void main(int argc, char* argv[])
{
 char * ap="hello";
 char * bp="how are you";
 cout<<"ap: "<<ap<<endl;
 cout<<"bp: "<<bp<<endl;

 swapstring(ap,bp);

 cout<<"after swapping..."<<endl;
 cout<<"ap: "<<ap<<endl;
 cout<<"bp: "<<bp<<endl;
}

原创粉丝点击