【问题标题】:Use typedef for passing parameters by reference使用 typedef 通过引用传递参数
【发布时间】:2016-03-25 03:08:29
【问题描述】:

我的学校项目说明中有这一部分:

hw_numbers.h 中定义类型 hw_number_array(用于通过引用将参数传递给函数)。要将数字存储在该数组中,请使用无符号长数组。

我的朋友给了我提示,它应该是这样的:

typedef unsigned long hw_number_array[];

谁能解释一下,我为什么要使用它来传递一个数组到函数?
如果不定义数组的实际大小,这种类型怎么可能存在?

【问题讨论】:

    标签: c arrays function typedef


    【解决方案1】:

    如果数组的大小被省略,这称为未知边界数组。只有某些地方可以使用它,但函数参数就是其中之一。有一个特殊的规则说,即使给数组一个边界,边界也会被忽略,参数等价于一个指针:

    void f(int []) // this means void f(int *)
    

    C++ 从 C 继承了这条规则。一些程序员认为它有助于记录旨在为参数传递数组而不是指向单个值的指针。

    调用这样的函数时,似乎可以通过引用传递数组:

    {
        int a[5];
        f(a); // actually passes an int pointer
    }
    

    但这实际上是一种错觉。数组衰减为指针,然后改为传递指针。

    【讨论】:

      【解决方案2】:

      您可以尝试以下代码:

      typedef unsigned long hw_number_array[];
      
      int main()
      {
          unsigned long myArray[100];
      
          setValue(myArray, 5, 10);
          unsigned long value = getValue(myArray, 5);
      
          return 0;
      }
      
      unsigned long setValue(hw_number_array a, int  index, unsigned long value)
      {
          a[index] = value;
      }
      
      
      unsigned long getValue(hw_number_array a, int  index)
      {
          return a[index];
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-07
        • 2011-08-21
        • 2012-08-31
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多