0

I have a function and want to return a 2d array:

int flip[5][5](int input[5][5]);

But it returns an error: no function error allowed (this is a translation)

How can I fix this?

This works:

void flip(int input[5][5]);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
black
  • 1,151
  • 3
  • 18
  • 46

3 Answers3

1

In this function declaration

void flip(int input[5][5]);

the parameter is implicitly adjusted to pointer to the first element of the array. So actually the function declaration looks like

void flip(int ( *input )[5] );

You may not return an array because arrays do not have a copy constructor.

You may return an array by reference provided that the array itself is not a local variable of the function.

So for example if your funciotn gets an array by reference then you may return this array from the function.

For example

int ( & flip(int ( &input )[5][5]) )[5][5];

You can wrap your array in a structure and return this structure along with the array.

For example

struct data
{
    int a[5][5];
};

data flip( int input[5][5] );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Use std::array<std::array<int, 5>, 5> instead of a built-in array type.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
1

The syntax for returning an array is ugly. You're better off using a typedef, or auto.

auto flip(int input[5][5]) -> int[5][5];

However the problem you have is, you aren't passing the array to the function as a reference or pointer, which won't work.

typedef int myArray[5][5];

void foo(myArray& arr) {
    //do stuff
}

int main() {
    int arr[5][5];
    foo(arr);
    return 0;
}

As an aside, working with arrays like this is tedious, you're better off using a container from the STL.

Ian
  • 24,116
  • 22
  • 58
  • 96
  • I chose the method with typedef and it work. Thanks! Still one question: wanted to create a copy of the input argument arr in the function foo. How can I do this? – black Nov 27 '15 at 16:51
  • The only way to "copy" the array is to put it on the heap (via `new`). If you create a local variable and try to return it from a function, it will get destroyed as soon as the function ends, that's no good. Keep in mind, if you use `new` you must use `delete` on it after, or you will have a memory leak. – Ian Nov 27 '15 at 17:25