有没有其他方法可以将指针的地址交换为交换值?
以下是一种方法。在这里,我们不会更改保存在地址上的值。
void Change_Address( int *&p, int *&pt)
{
int *pp;
pp = p;
p = pt;
pt= pp;
}
int main(void)
{
int a =3, b = 4, *p, *p1;
p = &a; p1 = &b;
printf("Values Before interchange %d %d\n", *p, *p1);
Change_Address(p, p1);
printf("Values after interchange %d %d", *p, *p1);
getch();
return 0;
}
答案 0 :(得分:2)
您的代码使用C++
的引用,在C
中您必须使用指针指针:
void Change_Address( int **p, int **pt)
{
int *pp;
pp = *p;
*p = *pt;
*pt= pp;
}
int main(void)
{
int a =3, b = 4, *p, *p1;
p = &a; p1 = &b;
printf("Values Before interchange %d %d\n", *p, *p1);
Change_Address(&p, &p1);
printf("Values after interchange %d %d", *p, *p1);
getch();
return 0;
}