www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - changing in two arrays

reply %u <asmasm hotmail.com> writes:
hi
I create two arrays and I want the change in one of them effects the other one.

i try

int[] array1 = [1, 2, 3, 4, 5];
int[] array2;
array2 = array1; // without .dup

assert(array1 == array2);
assert(array1 is array2); // here i am confused because 'is' mean thay have
the same address or what?

array2 ~= 6;
assert(array1 == [1, 2, 3, 4, 5]); // here is the problem
assert(array2 == [1, 2, 3, 4, 5, 6]);
Jun 26 2011
parent reply simendsjo <simen.endsjo pandavre.com> writes:
On 26.06.2011 13:59, %u wrote:
 hi
 I create two arrays and I want the change in one of them effects the other one.

 i try

 int[] array1 = [1, 2, 3, 4, 5];
 int[] array2;
 array2 = array1; // without .dup

 assert(array1 == array2);
 assert(array1 is array2); // here i am confused because 'is' mean thay have
 the same address or what?

 array2 ~= 6;
 assert(array1 == [1, 2, 3, 4, 5]); // here is the problem
 assert(array2 == [1, 2, 3, 4, 5, 6]);

The runtime will duplicate array2 to avoid array stomping. Steven Schveighoffer wrote a nice article on arrays you should read: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle
Jun 26 2011
parent Steven Schveigoffer <schveiguy yahoo.com> writes:
simendsjo Wrote:

 On 26.06.2011 13:59, %u wrote:
 hi
 I create two arrays and I want the change in one of them effects the other one.

 i try

 int[] array1 = [1, 2, 3, 4, 5];
 int[] array2;
 array2 = array1; // without .dup

 assert(array1 == array2);
 assert(array1 is array2); // here i am confused because 'is' mean thay have
 the same address or what?

 array2 ~= 6;
 assert(array1 == [1, 2, 3, 4, 5]); // here is the problem
 assert(array2 == [1, 2, 3, 4, 5, 6]);

The runtime will duplicate array2 to avoid array stomping. Steven Schveighoffer wrote a nice article on arrays you should read: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle

This can happen, but in this case, the two slices in fact point at the same data. The issue here is that the user is expecting the slice type to have full reference semantics. The slice type has its own length -- they do not share the length. So making one longer (by appending in this case) does not change the length of the other.it is a common misconception from people who come from languages that have a full reference array type. -Steve
Jun 26 2011