我想了解指针工作的本质。并有一个简单的交换函数示例。首先是按预期工作,第二个失败。 我无法理解第二个函数swap2()。我成功地交换了地址,但在函数退出后,值保持不变...... 为什么呢?
void swap1(int *x, int *y);
void swap2(int *x, int *y);
void startSwapExample() {
int a = 10;
int b = 20;
printf("a = %i, b = %i\n", a, b);
swap1(&a,&b);
printf("a = %i, b = %i\n", a, b);
printf("\n================\n");
int c = 10;
int d = 20;
printf("c = %i, d = %i\n", c, d);
swap2(&c,&d);
printf("c = %i, d = %i\n", c, d);
}
void swap1(int *x, int *y) {
printf("x = %i, y = %i\n", *x, *y);
int temp = * x;
* x = * y;
* y = temp;
printf("x = %i, y = %i\n", *x, *y);
}
void swap2(int *x, int *y) {
printf("x = %i, y = %i\n", *x, *y);
int * temp = x;
x = y;
y = temp;
printf("x = %i, y = %i\n", *x, *y);
}
该计划的输出:
a = 10, b = 20
x = 10, y = 20
x = 20, y = 10
a = 20, b = 10
================
c = 10, d = 20
x = 10, y = 20
x = 20, y = 10
c = 10, d = 20
Process finished with exit code 0
答案 0 :(得分:2)
在swap2中,您正在交换指针x和y,这两者都只存在于swap2函数的范围内。
当函数返回时,指针x和y不再存在,你对指针所做的任何操作(与指针指向的值相反)都没有效果。
答案 1 :(得分:0)
swap2()函数根据您的预期不起作用,原因如下。
void swap2(int *x, int *y) {
printf("x = %i, y = %i\n", *x, *y);
int * temp = x;
x = y;// x holding y
y = temp;// y holding x but not in main() function, only in swap2()
printf("x = %i, y = %i\n", *x, *y); // here you are getting expected output but not in main() function
}
在swap2()函数中它是交换但是修改不会影响main()函数,因为temp和x&你是本地指针&并且你没有取消引用任何东西,所以在main()中它将是相同的。