a struct as an multidimensional array index

Ali Çehreli acehreli at yahoo.com
Fri Jun 10 17:13:51 UTC 2022


On 6/10/22 08:01, Ali Çehreli wrote:

 > I still don't understand the reason though. The rows would be copied
 > without ref but should retain their type as bool[3], a static array. (?)

Ok, now I see the very sinister problem: It is a disaster to combine 
static array lambda parameters with the laziness of range algorithms. 
The following program prints garbage because by the time writeln prints 
the elements, those elements are on invalid places on the stack:

import std;

void main() {
   int[3][3] arr;

   writeln(
     arr[]                              // Have to slice
     .map!(row => row[]                 // Have to slice
           .map!(element => element))
   );
}

The output is garbage element values.

The programmer must take the parameter of the outer map by reference so 
that the elements are referring to actual elements in 'arr':

     .map!((ref row) => /* ... */

I don't think I realized this issue before, which may be caught by 
various combinations of safety compiler switches, which I haven't tried yet.

Ali



More information about the Digitalmars-d-learn mailing list