Passing a 2D array to a function in C++ as an array or pointer

I recently had an opportunity to experience the joys of passing 2D arrays (both as themselves and as pointers) to functions in C++.

Both of my examples here assume you already know the size of your 2D array (3×3, in this case).

int array[3][3] = {{0,0,0},{0,0,0},{0,0,0}};

Passing a 2D array to a function in C++

Notice the empty first set of brackets. For some reason, C++ only needs to know the columns. It can figure out the rows on its own (though it won’t break if you do include the row size).

int array[3][3];

void doStuff(int arr[][3]) {
   //accessing stuff inside it
   int someCellData = arr[0][0];
}

doStuff(array);

Passing a pointer to a 2D array to a function in C++

array[3][3];
int (*p_array)[3][3] = &array;

void doStuff(int (*arr)[3][3]) {
    //accessing stuff inside it
    int someCellData = (*arr)[0][0];
}
doStuff(p_array); //notice you pass it without the *

Additional notes on passing a pointer to a 2D array to a function in C++

When you declare and define the pointer to the array, you have to include the rows and columns sizes in accompanying square brackets.

If you don’t, you’ll get this error on that pointer’s definition line when you compile:

cannot initialize a variable of type 'int (*)' with an rvalue of type 'int (*)[3][3]'

So, don’t define your pointer to your 2D array like this:

int (*p_array) = &array; //wrong!

Do it like this:

int (*p_array)[3][3] = &array; //include rows & columns

More reading

These Stack Overflow queries helped me figure this out: