Home > Backend Development > C++ > How to Correctly Pass References to Two-Dimensional Arrays in C ?

How to Correctly Pass References to Two-Dimensional Arrays in C ?

Mary-Kate Olsen
Release: 2024-11-07 04:59:02
Original
399 people have browsed it

How to Correctly Pass References to Two-Dimensional Arrays in C  ?

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>
Copy after login

This prototype generates an error from g :

error: expected ‘,’ or ‘...’ before ‘*’ token
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template