Chronicle
Chronicle

Reputation: 1645

How do you declare a function in which you pass a multidimensional array by reference

I have a grid that I want to pass to another function in which I display it. However, I can't seem to figure out how I would declare that function, to which a multidimensional array is passed by reference.

void foo(bool[][]&); //INCORRECT: how is a correct way to declare this function?

// rest of code :

int main(){
    bool grid[50][50] = {false};
    foo(grid);
    return 0;
}

void foo(bool& grid[][]){
    // do things
}

This should be an elementary question but I'm having a lot of trouble finding a solution.

Upvotes: 1

Views: 82

Answers (2)

Shoe
Shoe

Reputation: 76240

You can use one of the followings:

void foo(bool(&grid)[][50]);
void foo(bool(&grid)[50][50]);

But since you have the extreme luck of using C++, you can avoid the C gibberish by using std::array instead:

void foo(std::array<std::array<bool, 50>, 50>&);

Yes, it's longer but it's much more descriptive and easy to remember. And if you are worried about "performance":

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.

And guess what? You can even create a templatized alias for it:

template<class T, std::size_t M, std::size_t N = M> using biarray = std::array<std::array<T, M>, M>;

that you can use in your function as:

void foo(biarray<bool, 50>&);

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

A reference to a 2D array type looks as follows:

T (&)[N][M]

So you want:

void foo(bool(&)[50][50]);

Note that the dimensions must be specified. For the function definition, it will look like:

void foo(bool (&grid)[50][50]) {

If you need to be able to use the function for 2D arrays of various sizes, you can make it a template over the dimensions:

template <std::size_t N, std::size_t M>
void foo(bool(&)[N][M]);

The template will be instantiated for each size of array you pass to it.

Upvotes: 6

Related Questions