On Tuesday, 4 June 2024 at 12:22:23 UTC, Eric P626 wrote:
I am currently trying to learn how to program in D. I thought
that I could start by trying some maze generation algorithms. I
have a maze stored as 2D array of structure defined as follow
which keep tracks of wall positions:
~~~
struct s_cell
{
bool north = true;
bool east = true;
bool south = true;
bool west = true;
}
~~~
I try to create a 2D array of fixed length and pass it in
parameter as a reference. Normally, in C, I would have used a
pointer as parameter, and pass the address of the array. Here,
I thought it would have been easier just to pass a slice of the
array, since a slice is a reference to the original array. So I
wrote the signature like this:
~~~
void main()
{ writeln("Maze generation demo");
s_cell [5][5] maze;
print_maze (maze);
}
void print_maze ( s_cell [][] maze )
{
}
~~~
My idea is that print_maze use a slice of what ever is sent in
parameter. Unfortunately, I get the following error message:
~~~
Error: function `mprmaze.print_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`
~~~
I tried to find a solution on the internet, but could not find
anything, I stumble a lot on threads about Go or Rust language
even if I specify "d language" in my search.
You have declared static array here, they cannot be implicitly
converted to dynamic arrays.
It is not very obvious but it is a part of language design to
avoid unnecessary GC allocations and for C compatibility reasons
in some cases (e.g. strings known at compile implicitly has null
appended to it to be able to pass pointer as is to C functions).
IIRC you can explicitly cast it to s_cell[][] to make it work but
it will allocate new array when you append to it.
Else is there other ways to pass an array as reference using
parameter modifiers like: ref,in,out ...
`ref` is exactly for that.
Else, can it be done the C way using pointers?
absolutely, even ref behind the scenes will basically do the same
thing anyway.