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]);
2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
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] );

1 Comment

A typedef or using declaration will make the syntax human-readable.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.