going beyond your bounds

MLT none at anon.com
Thu May 21 01:51:16 PDT 2009


After a discussion on digitalmars.D I played with arrays a bit. Look at the following code:
		int[] a = [1,2,3,4,5,6,7,8,9] ;
		int[] b = a ;
		a ~= 10 ;
                b ~= 11 ;
		b[0] = 12 ;
		Stdout(b).newline ;
		Stdout(a).newline ;

The result is:
[12, 2, 3, 4, 5, 6, 7, 8, 9, 11]
[12, 2, 3, 4, 5, 6, 7, 8, 9, 11]

Which means that even though b was set only to a[0..10], after expanding b, also has direct access to element a[10]. But
		int[] a = [1,2,3,4,5,6,7,8,9] ;
		int[] b = a ;
		a ~= 10 ;
		b.length = b.length+1 ;
		b[0] = 11 ;
		Stdout(b).newline ;
		Stdout(a).newline ;

Gives 
[11, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[11, 2, 3, 4, 5, 6, 7, 8, 9, 0]


Now b is expanded in length, but a side effect is that a[10] is set to 0 (i.e. initialized).

In the end, I think b can only see things that happen to a[10] after it expanded, but not before. It seems there is no way for the following to work:
		int[] a = [1,2,3,4,5,6,7,8,9] ;
		int[] b = a ;
		a ~= 10 ;

At this point, element a[10]=10 will never be visible to b. b can expand to it, but by doing that, a[10] will be overwritten.

Is this on purpose? It could also be useful to have b.length=b.length+1 which only initializes memory that has not been initialized before.




More information about the Digitalmars-d-learn mailing list