www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 1493] New: Problem with dynamic array

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=1493

           Summary: Problem with dynamic array
           Product: D
           Version: 1.021
          Platform: PC
        OS/Version: Windows
            Status: NEW
          Severity: major
          Priority: P2
         Component: DMD
        AssignedTo: bugzilla digitalmars.com
        ReportedBy: keystuffs netscape.net


The dynamic array seems to be shared with all instances of a class:

class A {
  int array1[]  = [0]; // dynamic array
  int array2[1] = [0]; // static array
}

int main(char[][] p) {
  A a1 = new A();
  A a2 = new A();

  a1.array1[0] = 10;
  std.stdio.writefln(a1.array1[0]); // write 10: OK
  std.stdio.writefln(a2.array1[0]); // write 10: should be 0 

  a1.array2[0] = 20;
  std.stdio.writefln(a1.array2[0]); // write 20: OK
  std.stdio.writefln(a2.array2[0]); // write 0:  OK

  return 0;
}

So I think that the variable array1 is shared with the objects a1 and a2.


-- 
Sep 11 2007
next sibling parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=1493


default_357-line yahoo.de changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |default_357-line yahoo.de





This isn't a bug.

An array, behind the scenes, is nothing but a pointer and a length.
So the dynamic array in your class gets initialized with a specific pointer and
length, which is the same for all instances because the _literal_ is the same.

The correct thing to do here is initialize the dynamic array in the
constructor, for example, by dup-ing it :)
 --downs


-- 
Sep 11 2007
prev sibling parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=1493


matti.niemenmaa+dbugzilla iki.fi changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
         Resolution|                            |INVALID




-- 
Sep 11 2007