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]) {
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Shibli
  • 5,879
  • 13
  • 62
  • 126
  • 3
    1D arrays are not automatically passed by reference... – Oliver Charlesworth Jan 07 '12 at 16:24
  • 1
    `int& arr[5][5]` -> `arr` is two dim array of type int ref , did you want that? – Mr.Anubis Jan 07 '12 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. – Shibli Jan 07 '12 at 16:29
  • 1D arrays are automatically passed the address of the array's first cell, it's reference like – yoni Jan 07 '12 at 16:29
  • @Mr.Anubis: Indeed. And such a thing doesn't even exist! – Oliver Charlesworth Jan 07 '12 at 16:30
  • Duplicate I guess : http://stackoverflow.com/questions/3155188/how-can-i-pass-a-multidimensional-array-to-a-function http://stackoverflow.com/questions/4683049/passing-multidimensional-arrays-to-function http://stackoverflow.com/questions/2828648/how-to-pass-a-multidimensional-array-to-a-function-in-c-and-c – Mr.Anubis Jan 07 '12 at 16:45
  • If you insist you can pass an array by reference, though. In this case, the last array dimension won't be ignored as it is otherwise. The type looks like this: int (&arr)[5][5] – Dietmar Kühl Jan 07 '12 at 21:47

2 Answers2

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • So do I need to put "&" for a 2D array if I want to modify the passed array? – Shibli Jan 07 '12 at 16:33
  • @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. – Luchian Grigore Jan 07 '12 at 16:37
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.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64