Passing References to Two-Dimensional Arrays in C
In C , passing references to two-dimensional arrays to functions can be tricky. Consider the following code:
<code class="cpp">const int board_width = 80; const int board_height = 80; void do_something(int[board_width][board_height]& array); //function prototype</code>
This prototype generates an error from g :
error: expected ‘,’ or ‘...’ before ‘*’ token
Error Explanation and Solution
This error indicates that something is missing where the asterisk (*) is placed. The declaration of the reference should use the following syntax instead:
<code class="cpp">void do_something(int (&array)[board_width][board_height]);</code>
By adding parentheses around array, we create a reference to the entire two-dimensional array. This allows the function do_something to modify the array directly.
Differences from Pointer Declaration
Note that this differs from declaring the parameter with a pointer type:
<code class="cpp">void do_something(int array[board_width][board_height]);</code>
In this case, only a pointer to the first sub-array of the two-dimensional array is passed, ignoring board_width. This is because arrays in C decay to pointers when they are passed to functions. As a reference is explicitly requested in the prototype, this declaration is incorrect.
Size Calculation
When using a reference, sizeof(array) within the function will yield sizeof(int[board_width][board_height]). In contrast, using the pointer-based declaration would result in sizeof(int(*)[board_height]), which corresponds to the size of a pointer.
The above is the detailed content of How to Correctly Pass References to Two-Dimensional Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!