On Tuesday, 19 January 2016 at 07:21:39 UTC, albert00 wrote:
On Tuesday, 19 January 2016 at 04:50:18 UTC, tsbockman wrote:
On Tuesday, 19 January 2016 at 03:20:30 UTC, albert00 wrote:
[...]

... what you're making is an array *of arrays*:

Maybe I was misunderstood, because in fact that is what I was making an array of arrays, but my problem in fact was in accessing it.

Like I said above:

I was declaring int[1][2] arr:

But to access I need to invert the columns like:

        arr2[0][0] = 1;
        arr2[1][0] = 2;


int[10][5] a; // An array of 5 (int[10])

Using your example, in my head I'd access the last element as:

a[9][4] but that would give me an error:

Error: array index 9 is out of bounds arr[0 .. 5]

So I need to invert a[4][9].

Again seems a bit strange "FOR ME" since I declare in one way and access the other way.

Try not to think in terms of columns and rows. It makes more sense to think of it in terms of *types*.

Given the following array declaration, which is an array of int:

int[2] nums;

Then any index into nums (such as nums[0]) is going to return an int. The same logic applies given this array declaration, which is an array of int[2]:

int[2][5] numArrays;

Then any index into numArrays is going to return int[2] (for example, numArrays[0]). In order to access the members of the returned array, we need one more index, so that int[0][1] is the second element of the first array. In other words, it's shorthand for:

int[2] arr = numArrays[0];
int num = arr[1];

Seen in this light, it is entirely consistent and not strange at all. It just takes some people a bit of effort to stop thinking in terms of C's multidimensional arrays so that it becomes second-nature to see it in this light. I was using D for quite some time before I finally got used to it.


Reply via email to