【发布时间】:2020-07-28 05:51:38
【问题描述】:
在开始之前,我想告诉你我正在学习编程。
在 C 中将变量传递给函数和将数组传递给函数有什么区别?
当我们将变量传递给函数时,我们只是传递函数的值。但是当我们传递一个数组时,我们以某种方式传递了一个指针,因为当我们在函数内部对数组进行一些更改时,实际的数组会发生变化。
为了让我的问题更清楚,我附上代码来解释我在问什么-
代码 1:
//Passing variable to function
#include<stdio.h>
void swap(int x, int y);
int main(void)
{
//Nothing is happening to real values of variables
int x, y;
x = 1;
y = 2;
swap(x, y);
printf("%d = x \n %d = y", x, y);
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
代码 2:
//Here you can see the values of arrays are swapped.
#include<stdio.h>
void swap(int arr[]);
int main(void)
{
int idx, array[2];
for(idx = 0; idx < 2; idx++ )
{
scanf("%d", &array[idx]);
}
swap(array);
for(idx = 0; idx < 2; idx++, printf("\n"))
{
printf("%d", array[idx]);
}
}
void swap(int arr[])
{
int temp;
temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}
也许我的问题还不清楚,但我只是想知道为什么数组的值会在 main 函数中发生变化,因为当我们调用函数时,我们只是传递了该变量的函数值。
【问题讨论】:
-
基本上就是你说的那样。你传递一个变量,然后传递变量的值。您传递一个数组,然后传递指向该数组第一个元素的指针。那么你的问题是什么?
-
因为数组是作为指针传递的,所以函数直接对数组的值进行操作。数组值不会复制到函数中。
-
数组通过指针传递有两个原因。 1)节省时间。 2)节省空间。如果数组有 2 个元素,这些都不重要。如果数组有 200 万个元素,这两者都很重要。
-
你基本上是对的。也许question about array to pointer decay 对你来说很有趣。
-
请注意,在第一个示例中,您不会在
main()中交换x和y的值。你只在swap()中更改x和y,这没什么用。
标签: c arrays function pointers parameters