【问题标题】:Are there other ways of passing array in a function? [duplicate]还有其他方法可以在函数中传递数组吗? [复制]
【发布时间】:2012-10-08 15:35:30
【问题描述】:

可能重复:
passing 2D array to function

我的问题与将数组作为 C++ 函数参数传递有关。我先举个例子:

void fun(double (*projective)[3])
{
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            projective[i][j]= i*100+j;
        }
}

int main()
{
    double projective[3][3];     

    fun(projective);
    for(int i=0; i<3; i++)
    {
        cout<<endl;
        for(int j=0; j<3; j++)
            cout<<projective[i][j]<<"   ";
    }


    return 0;
}

在示例中,fun 的传递参数是一个数组,我想知道是否还有其他方法可以传递这个参数。谢谢!

【问题讨论】:

    标签: c++


    【解决方案1】:

    fun 接受一个指向 3-double 数组的指针,它假定(依赖于调用者)这指向至少 3 个 3-double 数组的数组的第一个元素。它确实如此,因为正如您所说,在main 中提供给调用的参数是一个数组。这会立即衰减为指向其第一个元素的指针。

    另一种选择是fun 采用指向 3x3-array-of-double 的指针,因为它假定无论如何大小,调用者确实有这样的野兽:

    void fun(double (*p_projective)[3][3])
    {
        for(int i=0; i<3; i++)
            for(int j=0; j<3; j++)
            {
                (*p_projective)[i][j]= i*100+j;
            }
    }
    

    使用fun(&amp;projective) 调用它。

    【讨论】:

      【解决方案2】:

      你不能像这样传递一个数组,它总是衰减到一个指针。但是,如果您在其中包装一个结构,则可以传递一个数组。这适用于 C 和 C++。在 C++ 中,您可以传递对数组的引用。在这两种情况下,数组都是固定大小的。

      // as a struct
      struct Array
      {
        int elems[10];
      };
      
      void func(Array a);
      
      // as a reference
      void func(int (&a)[10]);
      

      【讨论】:

        【解决方案3】:

        如果您愿意,也可以只使用基指针并自己进行偏移,假设您的数组已分配或声明为具有 dim*dim 元素。

        void fun(double *projective, size_t dim)
        {
            for(size_t i=0; i<dim; i++)
                for(size_t j=0; j<dim; j++)
                    projective[i*dim+j] = i*100+j;
        }
        
        int main(int argc, char *argv[])
        {
            double ar[5*5];
            fun(ar, 5);
            return 0;
        }
        

        有很多方法可以做到这一点,这只是一种,但通常是最容易理解的(我通常使用 std::vector 作为后端)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-19
          • 2014-09-17
          • 2011-02-19
          • 2014-10-24
          • 1970-01-01
          • 2015-12-12
          • 2021-09-15
          • 1970-01-01
          相关资源
          最近更新 更多