Return array in a function Return array in a function arrays arrays

Return array in a function


In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:

int fillarr(int arr[])

Is kind of just syntactic sugar. You could really replace it with this and it would still work:

int fillarr(int* arr)

So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:

int* fillarr(int arr[])

And you'll still be able to use it just like you would a normal array:

int main(){  int y[10];  int *a = fillarr(y);  cout << a[0] << endl;}


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.


In C++11, you can return std::array.

#include <array>using namespace std;array<int, 5> fillarr(int arr[]){    array<int, 5> arr2;    for(int i=0; i<5; ++i) {        arr2[i]=arr[i]*2;    }    return arr2;}