Shibli
Shibli

Reputation: 6149

pass multidimensional array c++

Do I need to put "&" when I pass a 2D array to a function or 2D arrays automatically do so by reference as 1Ds.

void fnc (int& arr[5][5]) {
}

Upvotes: 0

Views: 1522

Answers (2)

Alan Stokes
Alan Stokes

Reputation: 18972

If you really want to pass the array by reference it would need to be:

void fnc(int (&arr)[5][5]);

Without the inner parentheses, as Mr Anubis says, you will be attempting to pass an array of references which is unlikely to be helpful.

Normally one would just write

void fnc(int arr[][5]);

(You could write arr[5][5], but the first 5 is ignored which can cause confusion.)

This passes the address of the array, rather than the array itself, which I think is what you are trying to achieve.

You should also consider a vector of vectors or other higher-level data structure; raw arrays have many traps for the unwary.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258648

It will be passed by value if you don't specify pass by reference &.

However arrays decay to pointers, so you're basically passing a pointer by value, meaning the memory it points to will be the same.

In common terms, modifying arr inside the function will modify the original arr (a copy is not created).

Also, 1D arrays also aren't passed "automatically" by reference, it just appears so since they decay to pointers.

Upvotes: 2

Related Questions