gpt4 book ai didi

与 C 指针混淆

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:13 25 4
gpt4 key购买 nike

 #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 函数没有改变值吗?

最佳答案

以下是 swapDoesNotWork 执行的所有修改:

 temp = ...
px = ...
py = ...

所有这些都是对局部变量的赋值。局部变量在函数返回时被销毁,因此 swapDoesNotWork 没有持久效果。它只会更改即将停止存在的变量。

另一方面,swap 包含这些行:

 *px = ...
*py = ...

这些是对分别由 pxpy 指向的位置的赋值。尽管 pxpy 本身是局部变量,但它们可以指向当前函数之外的变量(在这种情况下,该函数被称为 swap(&x, &y),因此它们指向 main 中的 xy 变量。

关于与 C 指针混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53937811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com