How to pass in reference a fixed array in parameter

Nick Treleaven nick at geany.org
Wed Jun 5 09:36:24 UTC 2024


On Wednesday, 5 June 2024 at 06:22:34 UTC, Eric P626 wrote:
> Now according to the book, it's possible to assign a slice from 
> a fixed array. This code will compile:
>
> ~~~
> int[12] monthDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 
> 30, 31 ];
> int[] a_slice = monthDays;
> ~~~

The element types are both int, so the compiler can slice the 
static array. As if you had written `a_slice = monthDays[];`.

> How come the assignment does not work when passing a parameter. 
> I tried the following and it failed:
>
> ~~~
> s_cell [5][5] maze;

The element type is s_cell[5].

> s_cell [][] sliced_maze = maze;

The element type of sliced_maze is s_cell[], so the element types 
are incompatible.

> ~~~
> void print_maze ( ref s_cell maze )
> void print_maze ( ref s_cell [][] maze )
> ~~~
>
> From what I found, arrays passed in parameters are always 
> passed by reference. So the ref keyword seems pointless.

You don't need `ref` to be able to read the array length and 
elements.
However, if you want to modify the array length, and have it 
affect the caller's dynamic array, you need `ref`.

>
> -------------------------------------------------------
>
> The only solution left is to use pointers. But even this does 
> not seems to work as in C. I created a function with different 
> pointer signature and they all fails.
>
> Normally in C, this would have worked:
>
> ~~~
> s_cell [5][5] maze;
> create_maze(&maze);

Pass `&maze[0][0]` instead.

> ~~~
> Error: function `mprmaze.create_maze(s_cell[][]* maze)` is not 
> callable using argument types `(s_cell[5][5]*)`
> cannot pass argument `& maze` of type `s_cell[5][5]*` to 
> parameter `s_cell[][]* maze`
> ~~~

s_cell[5][5] cannot implicitly convert to s_cell[][].

> Now I think it expect a 2D array of pointers instead of a 
> pointer on a 2D array.
>
> It's also not clear if there is a difference between those 2 
> notations:
>
> ~~~
> &maze
> maze.ptr
> ~~~

&maze is a pointer to s_cell[5][5].
maze.ptr is a pointer to s_cell[5]. `.ptr` means a pointer to the 
first element of the array.



More information about the Digitalmars-d-learn mailing list