how can I get a reference of array?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 4 22:58:09 PST 2015


On 02/04/2015 10:42 PM, zhmt wrote:
> Here is a simple code snippet:
> class A {
>      public int[] arr;
> }
>
> class B {
>      public int[] arr;
> }
>
> void main()
> {
>      int[] arr;
>
>      A a = new A;
>      B b = new B;
>      a.arr = arr;
>      b.arr = arr;
>
>
>      arr ~= 1;
>      arr ~= -2;
>
>      foreach(data; a.arr)
>      {
>          writeln(data);
>      }
>
>      foreach(data; b.arr)
>      {
>          writeln(data);
>      }
> }
>
> it prints nothing, I know that a.arr and b.arr are all slices of arr.
>
> But if a and b want to reference the global arr, it means that any
> changes in arr will be seen by a and b, and vice versa.
>
> How to?
>
> Thanks ahead.

First, in order to get what you want, add 4 starts and 2 ampersands so 
that there is one array and two pointers to it:

import std.stdio;

class A {
     public int[] * arr;    // <-- *
}

class B {
     public int[] * arr;    // <-- *
}

void main()
{
     int[] arr;

     A a = new A;
     B b = new B;
     a.arr = &arr;          // <-- &
     b.arr = &arr;          // <-- &


     arr ~= 1;
     arr ~= -2;

     foreach(data; *a.arr)  // <-- *
     {
         writeln(data);
     }

     foreach(data; *b.arr)  // <-- *
     {
         writeln(data);
     }
}

The output:

1
-2
1
-2

Appending to a slice breaks its sharing relationship with other slices. 
The following article is very informative:

   http://dlang.org/d-array-article.html

Ali



More information about the Digitalmars-d-learn mailing list