Return array in a function

后端 未结 19 2307
清酒与你
清酒与你 2020-11-22 05:23

I have an array int arr[5] that is passed to a function fillarr(int arr[]):

int fillarr(int arr[])
{
    for(...);
    return arr;
         


        
19条回答
  •  [愿得一人]
    2020-11-22 06:03

    C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.

    int *fillarr( int arr[] ) { // arr "decays" to type int *
        return arr;
    }
    

    You can improve it by using an array references for the argument and return, which prevents the decay:

    int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
        return arr;
    }
    

    With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:

    array< int, 5 > &fillarr( array< int, 5 > &arr ) {
        return arr; // "array" being boost::array or std::array
    }
    

    The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.

提交回复
热议问题