0

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]) { } 
7
  • 3
    1D arrays are not automatically passed by reference... Commented Jan 7, 2012 at 16:24
  • 1
    int& arr[5][5] -> arr is two dim array of type int ref , did you want that? Commented Jan 7, 2012 at 16:27
  • I mean that but interestingly in my code I pass by value but after the function ends the values of arr become changed. Commented Jan 7, 2012 at 16:29
  • 1D arrays are automatically passed the address of the array's first cell, it's reference like Commented Jan 7, 2012 at 16:29
  • @Mr.Anubis: Indeed. And such a thing doesn't even exist! Commented Jan 7, 2012 at 16:30

2 Answers 2

2

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.

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

2 Comments

So do I need to put "&" for a 2D array if I want to modify the passed array?
@Shibli that's not at all what I said. A straight-forward answer is you can pass it without the reference and it will still be modified outside. But try to understand the answer as it will be much more helpful in the long-run.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.