指针交换

来源:百度知道 编辑:UC知道 时间:2024/05/21 10:53:32
请问各位高手,下面的程序为什么a,b的值不能交换过来啊
void test(int *o,int *p)
{
int *t;
t=o;
o=p;
p=t;

}
void main()
int a(1),b(2);
test(&a,&b);
cout<<a<<endl<<b<<endl;
}
谢谢各位回答,但是我按照这么改
*t=*o; *o=*p; *p=*t;
程序会挂掉,请问这个是怎么回事?

这样改:
void test(int *o,int *p)
{
int t;
t=*o;
*o=*p;
*p=t;

}
void main()
int a(1),b(2);
test(&a,&b);
cout<<a<<endl<<b<<endl;
}

是t=*o;
*o=*p;
*p=t;
不是*t=*o; *o=*p; *p=*t;

//指针传递其实也是按值传递的,这个你可以改成
#include<iostream.h>
void test(int *o,int *p)
{
int t;
t=*o;
*o=*p;
*p=t;

}
void main()
{
int a(1),b(2);
test(&a,&b);
cout<<a<<endl<<b<<endl;
}

你只是把指针交换而已,原本的值并没有变啊。把它改为指针解引用后的值交换就可以了。
*t=*o; *o=*p; *p=*t;

不能