将数组作为参数传递给 C 中的函数 [英] Passing an array as an argument to a function in C

查看:31
本文介绍了将数组作为参数传递给 C 中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote a function containing array as argument, and call it by passing value of array as follows.

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

What I found is though I am calling arraytest() function by passing values, the original copy of int arr[] is changed.

你能解释一下原因吗?

推荐答案

当传递一个数组作为参数时,这个

When passing an array as a parameter, this

void arraytest(int a[])

意思和

void arraytest(int *a)

所以你正在修改 main 中的值.

so you are modifying the values in main.

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

For historical reasons, arrays are not first class citizens and cannot be passed by value.

这篇关于将数组作为参数传递给 C 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆