现在的位置: 首页 > 综合 > 正文

swap函数的低级错误写法

2013年07月10日 ⁄ 综合 ⁄ 共 617字 ⁄ 字号 评论关闭
#include<iostream>
using namespace std;


void swap(int &a,int &b)
{
   // cout<<"citation"<<endl;
    int t=a;
    a=b;
    b=t;
}


/*
void swap(int *a,int *b)
{
    cout<<a<<"\t"<<b<<endl<<endl;

    
    cout<<"address"<<endl;
    cout<<*a<<"\t"<<*b<<endl;

    int *t = a;

    cout<<t<<endl;

    a=b;
    cout<<a<<endl;

    b=t;
    cout<<b<<endl;

    cout<<*a<<"\t"<<*b<<endl;
}
*/



void swap(int *a,int *b)
{
   // cout<<"address"<<endl;
    int t = *a;
    *a = *b;
    *b = t;
}


int main()
{
    int a=10;
    int b=20;

    swap(a,b);
    cout<<a<<"\t"<<b<<endl<<endl;
    
    //cout<<&a<<"\t"<<&b<<endl;
    
    swap(&a,&b);
    cout<<a<<"\t"<<b<<endl;
    
    //cout<<&a<<"\t"<<&b<<endl;
    return 0;
}

注释掉的swap函数,在函数体里面继续使用指针操作,函数的参数是指针,交换这两个指针,但是指针的内容是没有变化的

所以原来的变量a,b的内容保存不变,变化的只是为了给swap函数传递参数,而是用的临时变量

抱歉!评论已关闭.