最近自学C语言时,发现在子函数中修改了地址可是在main中又自动恢复。
#include <stdio.h>
int P_app(int *A,int *B)
{
int *C = NULL;
printf("2\nA=%p\nB=%p\n", A, B);
C = A;
A = B;
B = C;
printf("3\nA=%p\nB=%p\n", A, B);
return 0;
}
int main()
{
int c, d;
int* a, * b;
a = NULL;
b = NULL;
c = 5;
d = 7;
a = &c;
b = &d;
printf("1\nc=%p\nd=%p\n", a, b);
P_app(a, b);
printf("4\nc=%p\nd=%p\n", a, b);
return 0;
}
为什么a,b的地址传进子函数P_app中在2中可以看到是地址已传进去了,并且在3中可以看出地址已经交换,为什么到4的时候传出来就又恢复成1了
函数中只是简单交换了A和B指针指向的地址,并没有交换a和b的地址,所以4中依然是原来的值,不是恢复的,而是就没有交换
#include <stdio.h>
int *P_app(int **A,int **B)
{
int *C = NULL;
printf("2\nA=%p\nB=%p\n", A, B);
C = *A;
*A = *B;
*B = C;
printf("3\nA=%p\nB=%p\n", A, B);
return 0;
}
int main()
{
int c, d;
int*p1, *p2;
p1= NULL;
p2= NULL;
c = 5;
d = 7;
p1 = &c;
p2 = &d;
printf("1\np1=%p\np2=%p\n", p1, p2);
P_app(&p1, &p2);
printf("4\np1=%p\np2=%p\n", p1, p2);
printf("5\nc=%d\nd=%d\n", *p1, *p2);
return 0;
}