不能交换两个变量的值的例子

不能交换的例子

//传入的是拷贝,不能交换的例子
#include<stdio.h>

void swap(char s1,char s2)
{
    char t;
    t=s1;
    s2=t;
    s1=s2;
}

void main()
{
    char s[]="abcdef";
        swap(s[0],s[1]);//传入的是拷贝
    printf("%s",s);
}

 

可以交换的例子 

//传入的是地址,可以交换的例子
#include<iostream>
#include<string>
using namespace std;

void swap(string &str)
{
    char t;
    t=str[0];
    str[0]=str[1];
    str[1]=t;
}
void main()
{
    string ch="abcd";
    swap(ch);
    cout<<ch<<endl;
}

 

posted @ 2014-01-22 10:46  yexuannan  阅读(149)  评论(0编辑  收藏  举报