Return an array in c++

前端 未结 11 2106
半阙折子戏
半阙折子戏 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:31

    As others said, there are better options like STL containers and the most interesting question is why you need to return the array to a function that already has it in scope.

    That being said, you can't pass or return arrays by value and need to avoid the array decaying to a pointer (see e.g. here), either by using pointers or references to it:

    int (&f(int (&arr)[3]))[3]
    {
        return arr;
    }
    

    If you don't want to hard-code the size, you can use template functions:

    template
    int (&f(int (&arr)[n]))[n]
    {
        return arr;
    }
    

提交回复
热议问题