【问题标题】:If we pass an array to a function in C, is it always passed by reference?如果我们将数组传递给 C 中的函数,它总是通过引用传递吗?
【发布时间】:2016-10-29 03:05:47
【问题描述】:

如果我们不想在main函数中改变数组的值,我们可以做什么? 例如:

    int func(int a[])
    {
         ------
         ---
    }

    int main()
    {
          int a[100];
          for (i = 0; i < 100; i++)
              scanf("%d", &a[i]);
          func(a);
    }

在此示例中,我们在 main 函数中放入数组的值将在 func 函数中替换。如何避免这种情况?

【问题讨论】:

    标签: c reference


    【解决方案1】:

    是的,数组总是“通过引用”传递;传递的值是指向数组第零个元素的指针。

    您可以通过将其设为const 来告诉编译器不允许更改:

    int func(const int a[])
    {
        …
        a[0] = 1;  // Compiler error - attempt to modify constant array
        …
    }
    

    请注意,将数组的大小(其中(已使用)元素的数量)作为额外参数传递给函数通常是个好主意:

    int func(int n, const int a[n])  // C99 or later
    int func(const int a[], int n)   // Classic argument order
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 2017-08-12
      • 2011-12-07
      相关资源
      最近更新 更多