On Wednesday, 10 October 2018 at 13:22:41 UTC, Chris Katko wrote:
int[][] data =
        [
                [1, 0, 1, 0, 0],
                [1, 0, 1, 0, 0],
                [1, 0, 1, 1, 1],
                [1, 0, 0, 1, 0],
                [5, 1, 1, 1, 0]
        ];

when drawn with data[i][j], prints the transpose of "data":

[1, 1, 1, 1, 5]
[0, 0, 0, 0, 1]
[1, 1, 1, 0, 1]
[0, 0, 1, 1, 1]
[0, 0, 1, 0, 0]

So, if I flip [i][j] and print a row of "j's", it'll be correct. It's very confusing and counter-intuitive to have to remember to swap i and j every time I use an array.

I guess when I load data from files, the i/j are already swapped and stay consistent, but when using an array in source code, they have to be flipped.

What you actually have there is an array of arrays, or a jagged array, and not a 2D, or multidimensional, array. If you dig into it, it's consistent with how array syntax works with all types. Consider the basics:

int i;
int[] intArray;

The type of `i` is `int`. If I want an array of ints, I put the brackets next to the type.

The type of `intArray` is `int[]`, but it contains elements of type `int`. We can visualize it with parens:

(int)[];

This indicates that `int` is the element type. We can apply the same rules to int[][]:

int[] singleArr;    // type is int[], element type int
int[][] doubleArr;  // type is int[][], element type ?

Again, using parens we cans the element type of `doubleArr`:

(int[])[];

So singleArr[0] returns the first `int`, and doubleArr[][0] returns the first int[]. Consistent.

So the syntax you are used to in C or C++ is /backwards/ in D.






Reply via email to