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[] 的原始副本已更改。

您能解释一下原因吗?

最佳答案

当将数组作为参数传递时,这

void arraytest(int a[])

意思完全一样

void arraytest(int *a)

所以您正在修改main中的值。

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

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

相关文章:

c - 收到错误消息说我的程序在 C 中崩溃了,即使它没有显示语法问题

c++ - 重新播种 std::rand/c++11 <random>

objective-c - 将函数作为参数传递给 Objective-C 方法

c - 在函数调用中向枚举添加 uint 的风险

c++ - 通过socket接收音频文件

c - 在 C 编程中访问 Raspberry PI 寄存器

javascript - 字符串到数组然后删除最后一个元素

javascript - 计算对象数组中的重复项并求和位于对象中的值

c - 是什么导致我的数组充满了不需要的数字

matlab - 矩阵 : Write a function in MATLAB that returns all of the positive integer numbers that satisfy the following property