#include <stdio.h>
void swap(int *x, int *y);
main()
{
int a = 5, b = 9;
int *pp = &a;
int *kk = &b;
swap(pp, kk);
printf("a=%d\nb=%d\n", *pp, *kk);
return 0;
}
void swap(int *x, int *y)
{
int *t;
t = x;
x = y;
y = t;
}
会发现,输出结果并没有交互,下面代码会更加信息的阐述这个过程
#include <stdio.h>
void swap(int *x, int *y);
main()
{
int a = 10, b = 20;
int *pp = &a;
int *kk = &b;
printf("a的地址%p----b的地址%p\n\n", &a, &b);
printf("pp的值%p----kk的值%p\n", pp, kk);
printf("pp的地址%p----kk的地址%p\n\n", &pp, &kk);
swap(pp, kk);
printf("a = %d\nb = %d", *pp, *kk);
return 0;
}
void swap(int *x, int *y)
{
int *t;
printf("x的值%p----y的值%p\n", x, y);
printf("x的地址%p----y的地址%p\n", &x, &y);
t = x;
x = y;
y = t;
}
到这里,才明白,指针终究还是一个变量,当这个变量传入函数的时候,C++还是会执行一个拷贝,生成一个临时对象,只不过该临时对象指向的内存地址与实参指向内存地址一样,所以我们想执行交互操作应该向下面代码这样,或者传递引用
#include <stdio.h>
void swap(int *p1, int *p2);
main()
{
int a = 5, b = 9;
int* pointer_1, *pointer_2;
pointer_1 = &a;
pointer_2 = &b;
swap(pointer_1, pointer_2);
printf("a=%d\nb=%d\n", a, b);
return 0;
}
void swap(int *p1, int *p2)
{
int t;
t = *p1;
*p1 = *p2;
*p2 = t;
}