Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a reference to a two-dimensional array to a function?

Tags:

c++

arrays

People also ask

Can you pass two-dimensional array to function in C?

A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows.


If you know the size at compile time, this will do it:

//function prototype
void do_something(int (&array)[board_width][board_height]);

Doing it with

void do_something(int array[board_width][board_height]);

Will actually pass a pointer to the first sub-array of the two dimensional array ("board_width" is completely ignored, as with the degenerate case of having only one dimension when you have int array[] accepting a pointer), which is probably not what you want (because you explicitly asked for a reference). Thus, doing it with the reference, using sizeof on the parameter sizeof array will yield sizeof(int[board_width][board_height]) (as if you would do it on the argument itself) while doing it with the second method (declaring the parameter as array, thus making the compiler transform it to a pointer) will yield sizeof(int(*)[board_height]), thus merely the sizeof of a pointer.


Although you can pass a reference to an array, because arrays decay to pointers in function calls when they are not bound to a reference parameters and you can use pointers just like arrays, it is more common to use arrays in function calls like this:

void ModifyArray( int arr[][80] ); 

or equivalently

void ModifyArray( int (*arr)[80] );

Inside the function, arr can be used in much the same way as if the function declaration were:

void ModifyArray( int (&arr)[80][80] );

The only case where this doesn't hold is when the called function needs a statically checked guarantee of the size of the first array index.


You might want to try cdecl or c++decl.

% c++decl
c++decl> declare i as reference to array 8 of array 12 of int
int (&i)[8][12]
c++decl> explain int (&i)[8][12]
declare i as reference to array 8 of array 12 of int
c++decl> exit

Syntax is not correct.

Lets take an example of 1D Array

 int a[] = {1,2,3};
 int (&p) [3] = a; // p is pointing array a 

So you can do same for 2D array as shown below

const int board_width = 80;
const int board_height = 80;
void do_something(int (&array) [board_width][board_height]);