a struct as an multidimensional array index

Ali Çehreli acehreli at yahoo.com
Sat Jun 11 14:54:19 UTC 2022


On 6/11/22 04:16, Salih Dincer wrote:

 > I think D is very consistent with our feelings. That is, the order in
 > memory is in the form of rows x columns.

Yet, there are no rows or columns because neither D nor C (nor C++) have 
multip-dimensional arrays. They all have arrays where elements are layed 
out in memory consecutively.

The type of the elements and what they represent is entilery up to the 
programmer.

 > But yes, in reverse(column x
 > row) when you set it up statically.

If you mean we can set up the memory in any way we want, I agree but 
again, since there are no mult-dimensional arrays, there cannot be the 
reverse of the order.

 > This sample code working on pointers
 > can be a proof:

If it's prooving that elemets are side-by-side, then it's by spec.

Here is an example where I have array where each element is a column:

import std.stdio;
import std.range;
import std.algorithm;

void main() {
   // I decide that this array represents
   // Three rows of two columns.
   int[][] arr;
   arr.length = 2;
   foreach (ref column; arr) {
     column.length = 3;
   }

   setFirstColumn(arr, 1);
   printArray(arr);
}

void setFirstColumn(int[][] arr, int value) {
   // The first element is my first column.
   arr[0][] = value;
}

void printArray(int[][] arr) {
   // Because stdout takes line-by-line,
   // we print a transposition.
   arr.transposed.writefln!"%-(%-(%s %)\n%)";
}

You may think that the final transposition is a trick. No, it was needed 
only because stdout takes line-by-line. If I used a library like 
ncurses, I could have printed my array exactly the way I used it.

The point is, there are no multi-dimensional arrays. Programmers use 
arrays as they need and sometimes the elements are arrays.

Ali



More information about the Digitalmars-d-learn mailing list