【发布时间】:2018-12-26 22:27:38
【问题描述】:
#include<stdio.h>
// Function to swap two values but does not work
void swapDoesNotWork (int *ptrX, int *ptrY);
// Function to swap two values and works fine
void swap (int *ptrX, int *ptrY);
void swap (int *px, int *py) {
int temp;
temp = *px;
*px = *py;
*py = temp;
}
void swapDoesNotWork (int *px, int *py) {
printf("\n\n");
int temp;
temp = *px;
px = py;
py = &temp;
}
int main() {
int x = 5;
int y = 10;
swapDoesNotWork(&x, &y);
printf("++++++++++++++++++\n");
printf("pre x:%d\n", x);
printf("pre y:%d\n", y);
printf("\n");
printf("After calling swapDoesNotWork(&x, &y)...\n");
printf("post x:%d\n", x);
printf("post y:%d\n", y);
printf("++++++++++++++++++\n\n");
x = 5;
y = 10;
printf("= = = = = = = = =\n\n");
printf("pre x:%d\n", x);
printf("pre y:%d\n", y);
swap(&x, &y);
printf("\n");
printf("After calling swap(&x, &y)...\n");
printf("post x:%d\n", x);
printf("post y:%d\n", y);
printf("= = = = = = = = =\n\n");
return 0;
上述程序编译执行后的输出为:
infi@linux% ./swap_test.o
++++++++++++++++++
pre x:5
pre y:10
After calling swapDoesNotWork(&x, &y)...
post x:5
post y:10
++++++++++++++++++
= = = = = = = = =
= = = = = = = = =
pre x:5
pre y:10
After calling swap(&x, &y)...
post x:10
post y:5
可以看出,swapDoesNotWork 函数似乎没有像 swap 函数那样更改值。
我是 C 语言的新手,主要来自脚本背景。有人可以帮我为什么swapDoesNotWork functon 没有改变值吗?
【问题讨论】: