passing a double array to a function

Started by
1 comment, last by Zahlman 17 years, 9 months ago
If I pass a DA to a function like this:

bool GameOver(int Position[7][6], int turn, int move, int Height)
{
 bool Win = false;
 //check coloums
  int InARow = 0;
  for(int r=0; r<6; r++)
   {
    if(Position[move][r] == turn)
 ...

But as a referance (int& Position[7][6]) it doesn't. Why? Thanks.
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky
Advertisement
Quote:Original post by daniel_i_l
If I pass a DA to a function like this:
*** Source Snippet Removed ***
But as a referance (int& Position[7][6]) it doesn't. Why?
Thanks.

bool GameOver(int Position[7][6], int turn, int move, int Height)

is actually the syntax for passing a pointer to an array of 6 integers. It's exactly the same as writing:
bool GameOver(int (*Position)[6], int turn, int move, int Height)

Whenever you type out an array with any number of dimensions in a parameter list, it's equivalent to a pointer to the type without the left-most dimension. In other words, even when you do:
bool GameOver(int Position[6], int turn, int move, int Height)

it is exactly the same as:
bool GameOver(int* Position, int turn, int move, int Height)

The left-most array dimension size is meaningless in the function header.

When you call such functions with an array, a pointer to the first element of the array is passed which is why you can access it intuitively in most situations. Keep in mind that you are not working with a copy of the array. The downside of this is that it implies that you may pass a pointer, or an array with any number of dimensions to the function and within the function you can only work with the argument as a pointer (so sizeof will yield the sizeof a pointer and attempting to pass the array to a function which takes a reference to an array of the originally desired size will not work, etc.).

That said, you can still explicitly pass an array by reference, preserving dimension information and the array type:
bool GameOver(int (&Position)[7][6], int turn, int move, int Height)

That is the proper syntax for passing the entire array by reference.
[boost]::array? :s

This topic is closed to new replies.

Advertisement