gpt4 book ai didi

c - 如何在 C 中传递参数以便可以更改值?

转载 作者:行者123 更新时间:2023-11-30 18:27:47 26 4
gpt4 key购买 nike

C 传递值而不是参数——这就是我被告知的,但我该如何解决这个问题呢?我就是不明白。

#include <stdio.h>

/* This will not work */

void go_south_east(int lat, int lon) {
lat = lat - 1;
lon = lon + 1;
}

int main() {
int latitude = 32;
int longitude = -64;
go_south_east(latitude, longitude);
printf("Now at: [%i, %i]\n", latitude, longitude);
printf("The log pointer is at %x\n", longitude);
}

它不会更新 main() 中的值— 他们保持在 32, -64,但应该是 31, -63。

最佳答案

默认情况下,C 将创建参数的副本并在函数内对其进行操作,函数结束后副本将不再存在。您想要做的是在参数中使用指针并取消引用它们以对指针指向的值进行操作。

这个主题可以帮助您更好地理解:What's the difference between passing by reference vs. passing by value?

这应该有效:

void go_south_east(int *lat, int *lon) {
*lat = *lat - 1;
*lon = *lon + 1;
}

int main() {
int latitude = 32;
int longitude = -64;
go_south_east(&latitude, &longitude);
printf("Now at: [%i, %i]\n", latitude, longitude);
}

关于c - 如何在 C 中传递参数以便可以更改值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52865234/

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