gpt4 book ai didi

c - 将数组传递给C中的函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:25 25 4
gpt4 key购买 nike

考虑以下 C 程序:

#include <stdio.h>

void swap(int []);

int main(void) {
int a[3] = {1, 2, 3};
swap(a);
printf("%d %d %d\n", a[0], a[1], a[2]);
swap(&a[1]);
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}

void swap(int x[]) {
int temp = x[0];
x[0] = x[1];
x[1] = temp;
}

谁能解释为什么下面的代码会给出输出
2 1 3
2 3 1

而不是
2 1 3
1 2 3

我理解 swap(a) 交换 a[0]a[1]。但我不太确定 swap(&a[1]) 是如何工作的。在这两种情况下,我们都将数组 a 传递给函数 swap,不是吗?所以我的假设是 swap(&a[1]) 应该再次交换 a[0]a[1],返回给我们原始顺序 2 3 1

编辑:这段代码是按预期编写的。我只是想看看如果我们将第一个元素以外的元素的地址传递给函数会发生什么。显然,如果我将 &a[n] 传递给函数,它会忽略 a[n] 之前的所有元素,并将 a[n] 视为第一个元素?

最佳答案

您的交换函数将一个整数的地址作为输入,并将该地址的元素与下一个地址的元素交换。

swap(a) is same as swap(&a[0])
It will swap element at index 0 with element at index 1.
Now your array becomes {2,1,3}
swap(&a[1]) swaps element at index 1 with element at index 2.
So your array now becomes {2,3,1}

请记住,当您传递一个数组时,实际上您传递的是索引 0 处的元素地址 (&a[0])。

关于c - 将数组传递给C中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27118927/

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