gpt4 book ai didi

c - 每种情况下 'x' 的值是多少?

转载 作者:行者123 更新时间:2023-11-30 21:03:48 24 4
gpt4 key购买 nike

我有以下类似 C 的程序,我试图计算出数组 x 的最终值:

  • 参数 x 按值传递。
  • 参数 x 通过引用传递。
  • 参数 x 通过 value-result 传递。

代码:

void swap(int[] list, int i, int j)
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}

void main()
{
int x[3] = {5, 2, 4};
swap(x, 1, 2);
}

如果我遵循正确,对于按值传递,在调用中我们...

swap(x, 1, 2)
{
temp = x[1] // temp now equals 2
x[1] = x[2] // x[1] now equals 4
x[2] = temp // x[2] now equals 2
}

...那么我们有以下内容,对吗?

x[3] == {5, 4, 2}

编辑:

我尝试在 ideone.com 上编译并收到:

prog.c:1:17: error: expected ‘;’, ‘,’ or ‘)’ before ‘list’
void swap(int[] list, int i, int j)
^
prog.c:8:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
void main()
^
prog.c: In function ‘main’:
prog.c:11:5: warning: implicit declaration of function ‘swap’ [-Wimplicit-function-declaration]
swap(x, 1, 2);
^

最佳答案

实际上,当你打电话时

swap(x, 1, 2);

您正在使用call-by引用,因为您传递的是参数x,它是一个指针到数组 x 的第一个元素。因此,这种交换技术将发挥作用,您将得到您所期望的结果,即元素现在的顺序为 {5,4,2}

关于c - 每种情况下 'x' 的值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532429/

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