array initialization problem

Jarrett Billingsley jarrett.billingsley at gmail.com
Fri Jan 16 13:41:54 PST 2009


On Fri, Jan 16, 2009 at 4:19 PM, Qian Xu <quian.xu at stud.tu-ilmenau.de> wrote:

> Can someone explain, why the values are different before they are inserted
> into a list?

The values are different _before you insert values into e2_.  Try
printing out the contents of e _after_ you put strings in e2, and
you'll notice it now has the same values as e2.

This is because arrays in D are by reference.  e and e2 point to the
same array (CLIST).  When you modify the contents of e2.list, the
modifications show up in e as well.

Accessing this.str is fine because they each point to different strings.

>    Cout.opCall("list: [");

Also, lol, opCall is an operator overload of ().  You aren't supposed
to call it directly, use:

Cout("list: [");

instead.


> void main()
> {
>  Entity e = new Entity();
>  e.list[0] = "111";
>  e.list[1] = "222";
>  e.str = "hello";
>  e.print();
>
>  Entity e2 = new Entity();
>  e2.list[0] = "333";
>  e2.list[1] = "444";

See, e.list and e2.list are the same array here.


More information about the Digitalmars-d-learn mailing list