&运算符,用于取一个对象的地址
*是一个间接寻址符,用于访问指针所指向的地址的值
int *ptr 定义一个指针
int b = *ptr 用于访问指针所指向的地址的值
& 与 * 是 一对互逆运算
//值传递,不会影响最终的结果
void swap(int x, int y) {
printf("交换前:x = %d, y =%d\n", x, y);
int tmp = x;
x = y;
y = tmp;
printf("交换后:x = %d,y = %d\n", x, y);
}
// 指针传递,变量的地址
void swap1(int* x, int* y) {
printf("交换前:x = %p, y =%p\n", x, y);
printf("交换前:*x = %d, *y =%d\n", *x, *y);
int tmp = *x;
*x = *y;
*y = tmp;
printf("交换后:x = %p, y =%p\n", x, y);
printf("交换后:*x = %d, *y =%d\n", *x, *y);
}
int main() {
int a = 2 , b =3;
printf("交换前:a = %d, b = %d\n", a, b);
swap(a,b);
printf("交换后:a = %d, b = %d\n", a, b);
printf("=======================\n");
a = 20 , b = 30;
printf("交换前:a = %d, b = %d\n", a, b);
printf("交换前:&a = %p, &b = %p\n", &a, &b);
swap1(&a,&b);
printf("交换后:a = %d, b = %d\n", a, b);
printf("交换后:&a = %p, &b = %p\n", &a, &b);
return 0;
}
交换前:a = 2, b = 3
交换前:x = 2, y =3
交换后:x = 3,y = 2
交换后:a = 2, b = 3
=======================
交换前:a = 20, b = 30
交换前:&a = 000000000022FE4C, &b = 000000000022FE48
交换前:x = 000000000022FE4C, y =000000000022FE48
交换前:*x = 20, *y =30
交换后:x = 000000000022FE4C, y =000000000022FE48
交换后:*x = 30, *y =20
交换后:a = 30, b = 20
交换后:&a = 000000000022FE4C, &b = 000000000022FE48
网友评论