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];


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

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:

One thought on “Passing a 2D array to a function in C++ as an array or pointer”

  1. Interesting. I’m also a C++ newbie and this post drove me to try out a few things.
    I have two suggestions:
    1) The initialization of the array on the first line may be a little verbose. I think the same thing can be achieved with

    array[3][3] = { };

    Imaging if you were starting with an array with dimensions in the dozens or hundreds. Not an exciting prospect with the first method…

    2) The possible reason why the row numbers can be omitted in the function definition could be attributed to the fact that the 0th index of any array, is actually an address (or some would refer to it as a pointer), with subsequent indices (i.e. the columns) being contiguous memory locations. I’m not sure about this, but you could experiment with your code to see whether the function will work REGARDLESS of the number of rows of the array that is passed as an argument. The result should be interesting.

    Thanks for another informative post. I learnt something new today.

Leave a Reply

Your email address will not be published. Required fields are marked *