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

标签 c arrays function parameters parameter-passing

我写了一个包含数组作为参数的函数, 并通过传递数组值来调用它,如下所示。

void arraytest(int a[])
{
    // changed the array a
    a[0] = a[0] + a[1];
    a[1] = a[0] - a[1];
    a[0] = a[0] - a[1];
}

void main()
{
    int arr[] = {1, 2};
    printf("%d \t %d", arr[0], arr[1]);
    arraytest(arr);
    printf("\n After calling fun arr contains: %d\t %d", arr[0], arr[1]);
}

我发现虽然我通过传递值调用 arraytest() 函数,但 int arr[] 的原始副本已更改。

你能解释一下为什么吗?

最佳答案

当传递数组作为参数时,this

void arraytest(int a[])

意思完全一样

void arraytest(int *a)

因此您正在修改 main 中的值。

由于历史原因,数组不是一等公民,不能按值传递。

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

相关文章:

c - linux 内核 `min` 宏

c - 使用指向字符的指针作为 strtok 的参数

javascript - 使用索引访问对象属性会给出 undefined

C++::成员函数数组

c - 以特定格式图表打印二叉搜索树。在 c

javascript - forEach 返回未定义 - 如何改为返回数组?

c - 使用fscanf填充一个char数组会更改另一个char数组的值

Python 函数意外修改外部函数中的变量

c - 计算一个值在数组中出现次数的最佳方法是什么?

c - 目标文件中 .bss 部分的必要性是什么?