Return an array in c++

前端 未结 11 2171
半阙折子戏
半阙折子戏 2021-01-02 12:14

Suppose I have an array

int arr[] = {...};
arr = function(arr);

I have the function as

 int& function(int arr[])
 {
//         


        
11条回答
  •  春和景丽
    2021-01-02 12:20

     int& function(int arr[])
    

    In this function arr is a pointer, and there's no way to turn it back to an array again. It's the same as

    int& function(int* arr)
    

    int arr[] = {...};
    arr = function(arr);
    

    Assuming the function managed to return a reference to array, this still wouldn't work. You can't assign to an array. At best you could bind the result to a "reference of an array of X ints" (using a typedef because the syntax would get very ugly otherwise):

    typedef int ten_ints[10];
    
    ten_ints& foo(ten_ints& arr)
    {
       //..
       return arr;
    }
    
    int main()
    {
        int arr[10];
        ten_ints& arr_ref = foo(arr);
    }
    

    However, it is completely unclear what the code in your question is supposed to achieve. Any changes you make to the array in function will be visible to the caller, so there's no reason to try to return the array or assign it back to the original array.


    If you want a fixed size array that you can assign to and pass by value (with the contents being copied), there's std::tr1::array (or boost::array). std::vector is also an option, but that is a dynamic array, so not an exact equivalent.

提交回复
热议问题