注册 登录
编程论坛 C++教室

我用指针来进行两个数交换,怎么就是出现错误,求指点??

小盗_发飙 发布于 2013-01-03 19:13, 602 次点击
#include<iostream>
using namespace std;

int swap(int *,int *);

int main()
{
    int *a,*b;
    int x,y;
    while (cin>>x>>y)
    {
    a=&x; b=&y;
    swap(a,b);
    cout<<*a<<" "<<*b<<endl;
    }
}

int swap(int *a,int *b)
{
    int *temp;
    temp=a;
    a=b;
    b=temp;
}
4 回复
#2
小盗_发飙2013-01-03 20:08
自己弄明白了。哈哈哈。

#include<iostream>
using namespace std;

int swap(int *&,int *&);

int main()
{
    int *a,*b;
    int x,y;
    while (cin>>x>>y)
    {
    a=&x; b=&y;
    swap(a,b);
    cout<<*a<<" "<<*b<<endl;
    }
}

int swap(int *&a,int *&b)
{
    int *temp;
    temp=a;
    a=b;
    b=temp;
}
原来是形参的变化不能影响主调函数的实参。
加个引用调用,就可以了!!
#3
liqingqinger2013-01-03 21:36
#include<iostream>
using namespace std;

int swap(int *,int *);

int main()
{
    int *a,*b;
    int x,y;
    while (cin>>x>>y)
    {
    a=&x; b=&y;
    swap(a,b);
    cout<<*a<<" "<<*b<<endl;
    }
}

int swap(int *a,int *b)
{
    int temp;如果把这个交换定义为指针变量 未对temp赋值 指向的单元是布可预见的
    temp=*a;//将a,b 的值互换
    *a=*b;
    *b=temp;
}
我是菜鸟
#4
qunxingw2013-01-03 22:10
temp变量尽量不用指针,否则就变复杂了。
#5
xs7653482013-01-06 16:34
建议用引用
void swap(int& a,int& b){
    int temp;
    temp = a;
    a = b;
    b = temp;
}
1