Home  >  Article  >  Backend Development  >  Why Does C Throw "expected ',' or '...' before '*' token" When Passing a Two-Dimensional Array By Reference?

Why Does C Throw "expected ',' or '...' before '*' token" When Passing a Two-Dimensional Array By Reference?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 00:41:021008browse

Why Does C   Throw

Passing a Reference to a Two-Dimensional Array

Problem

When attempting to pass a reference to a two-dimensional array to a function in C , users may encounter the error "expected ',' or '...' before '*' token" from g . The question arises: what does this error indicate and how can it be resolved?

Solution

The error indicates that the function prototype for do_something() is incorrect. To pass a reference to a two-dimensional array with known dimensions at compile time, the following syntax should be used:

<code class="cpp">void do_something(int (&array)[board_width][board_height]);</code>

Declaring the parameter as int array[board_width][board_height]; would instead pass a pointer to the first sub-array of the array, which is not the desired functionality in this case.

Explanation

The reference syntax &array ensures that the actual array is passed by reference, allowing the function to modify the array's contents directly. The notation int (&array)[board_width][board_height] specifies that the parameter array is a reference to a two-dimensional array with dimensions of board_width and board_height.

By contrast, int array[board_width][board_height]; declares the parameter array as a pointer to a one-dimensional array of board_height integers, thereby ignoring the second dimension of the array. This results in the reported error because the syntax is incorrect.

The above is the detailed content of Why Does C Throw "expected ',' or '...' before '*' token" When Passing a Two-Dimensional Array By Reference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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