Passing 3D array as a 2D parameter

I'm working on a project where I need to reuse functions that were meant for a 2D array but with a 2D portion of a 3D array. Say I have a 3D array called boards (boards[9][9][3]) I want this array to contain 4 2D arrays that are 9x9. I then want to pass one of these 2D arrays to another function that looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
   int board[9][9][3]; // 3D array 


   function(board[2]); // I want to be able to pass one 2D part of it here
}

void function(int board[][9])
{
   //do stuff with 2D array
}


I found some other forms that said to pass it by using "function(board[2])" as shown above but I keep getting the following error:

test.cpp: In function ‘int main()’:
test.cpp:63:23: error: cannot convert ‘int (*)[9][3]’ to ‘int (*)[9]’ for argument ‘1’ to ‘void function(int (*)[9])’
function(board[2]);

If someone could help me understand what I may be doing wrong I would really appreciate it!
Multidimensional arrays are syntax/code poison. I strongly recommend you abandon this idea and encapsulate these structures in a class or something.

That said... to actually answer your question...

Short answer

You have the wrong parameter for 'function'. You must retain the inner array sizes. So in order to pass board[2] to 'function', you must define function like this:

void function(int board[][3]) // <- note: 3, not 9



Long Answer

int board[9][9][3];

A 3D array is an array of arrays of arrays.
So this is an array of 9 arrays of 9 arrays of 3 ints.

To clarify this... let's assign a name to these types:
1
2
3
4
int a;  // type = 'int'
int b[3];  // type = 'int3', or an array of 3x int
int c[9][3]; // type = 'int93' or an array of 9x int3
int d[9][9][3];  // type = 'int993' or an array of 9x int93 


'board' in this case would be an 'int993'

board[2] is accessing the [2] element in the board array.
Since board is an int993, which is an array of int93s, this means that 'board[2]' is of type 'int93'

Since array names can be cast to a pointer to their first element... this means board[2] (while it is an int93) can be cast to a pointer to an int3

Your function:

1
2
// I'm changing the param name to 'param' so as not to confuse it with main's 'board'
void function(int param[][9])


Here, param is a pointer to an int9.
We are giving it an array name which is being cast to a pointer to an int3

An int3 is not an int9

Therefore these pointer types are incompatible, and you will get the error you are seeing.
Awesome!

That made sense. From there I was able to figure out that I was declaring my array backwards. After changing it to board[3][9][9] I was able to pass board[2] or board[1] to function.

Thanks so much for your help!
Topic archived. No new replies allowed.