Multi dimensional array question.
Lars T. Kyllingstad
public at kyllingen.NOSPAMnet
Tue Jul 13 03:33:44 PDT 2010
On Mon, 12 Jul 2010 17:23:16 -0400, Heywood Floyd wrote:
> bearophile Wrote:
>
>> Heywood Floyd:
>> > This had me crazy. I ended up putting the brackets on the variable,
>> > like
>> > int marr[3][5];
>> > then it worked like
>> > marr[2][4] = 9;
>>
>> That's present only for compatibility with C syntax, this means that
>> you can use it to perform a quicker port of C code to D, but you are
>> supposed to later convert it to D-style array definitions. See also:
>> http://www.digitalmars.com/webnews/newsgroups.php?
art_group=digitalmars.D&article_id=113185
>>
>> Bye,
>> bearophile
>
> Aha, good to know! Thanks!
> (So this might go away in the future? Or require a -cstyle compile
> flag?)
>
> ***
>
> I have a feeling this "backwards"-array stuff is gonna be one of the
> things my brain will repel for as long as it can.
>
> To me, it seems equal to saying "you declare a function like:
>
>
> void foo(string name, int age){
> //... }
>
>
> And then call it by doing
>
> foo(90,"Benny")
>
> and this makes sense because the arguments are actually pushed on the
> stack in reverse at runtime, so they arrive in the correct order in the
> function. And this is especially important with tuples." or something.
>
> Ok, I understand this has some deep purpose that I still don't
> understand, I'm just, yeah. *tear* (Although this is way out of my
> league: For instance, if a T is an int[3][4], then why can't T[string]
> be a int[string][3][4], and be accessed with arr["a"][2][3]? Seems just
> like a matter of taste?)
But then arrays would be different from all other types! If you have an
array of 3 Ts, that is written T[3], regardless of what T is. Now
consider these two cases:
A. T is an int. Then T[3] becomes int[3].
B. T is an int[string]. Then T[3] becomes int[string][3].
In case A, the first element of the array is accessed like this:
int[3] a;
int firstA = a[0];
Since a is an array of int, firstA is of course an int.
But then, since b is an array of int[string], we have
int[string][3] b;
int[string] firstB = b[0];
If we again want to access element "foo" of the associative array which
is firstB, we write firstB["foo"]. And so we have the following three
ways to get to that element, which *must* be equivalent because that's
how the language is defined:
// Using firstB as an intermediate step
int[string] firstB = b[0];
int x = firstB["foo"];
// Drop the intermediate variable firstB
int x = (b[0])["foo"];
// Drop the redundant parentheses
int x = b[0]["foo"];
So you see, it can't be any other way than the way it is. :)
-Lars
More information about the Digitalmars-d-learn
mailing list