question about passing associative array to a function

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 11 09:54:17 PDT 2014


On 05/11/2014 07:46 AM, rbutler wrote:

 > I have searched and can not understand something about passing AAs to a
 > function.
 > I have reduced the gist of the question to a tiny program below.
 > If I put "ref"  in the function stmt it works, i.e.:
 >          ref int[int] aa
 > My confusion is that AAs are supposed to be passed as refs anyway, so 
I do
 > not understand why I should have to use ref to make it work.
 >
 > Related, it also works if I UN-comment the line    d[9] = 9;
 >
 > Thanks for any helpful comments you can make.
 > --rbutler
 >
 > import std.stdio;
 >
 > void test(int[int] aa, int x) {
 >      aa[x] = x;
 >      aa[8] = 8;
 > }
 >
 > void main() {
 >      int[int] d;
 >      writeln(d.length);
 >      // d[9] = 9;
 >      test(d, 0);
 >      writeln(d);
 > }

The problem is with the initial state of associative arrays, which 
happens to be null. When AAs are copied when null, both copies are null, 
not being associated with anything, not even an initial table to store 
the hash buckets in. As a result, null AAs cannot be references to each 
other's (non existent) data.

When a null AA starts receiving data, it first creates its own data 
memory but the other one cannot know about that data.

ref parameter works because then there is only one AA to speak of.

d[9] entry works as well because then the first AA is not null.

Ali



More information about the Digitalmars-d-learn mailing list