Pointers or copies?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Dec 21 13:38:49 PST 2006


Frits van Bommel wrote:
> Chris Nicholson-Sauls wrote:
>> void drop (T) (inout T[] haystack, size_t index)
>> in {
>>   assert(index < haystack.length, ".drop() called with index greater 
>> than array length");
>> }
>> body {
>>   if (index != haystack.length - 1) {
>>     memmove(&(haystack[index]), &(haystack[index + 1]), T.sizeof * 
>> (haystack.length - index));
>>   }
>>   haystack.length = haystack.length - 1;
>> }
> 
> Doesn't that move one element from beyond the end of the array?
> 
> Array [0, 1, 2], drop element at index 1:
>     memmove(&(array[1]), &(array[2]), int.sizeof * (3-1));
> Moves 2 elements, starting at the 3rd element (element at index 2) of a 
> 3-element array...

Doesn't seem to.  Illustrative program:

# import cashew .utils .array ;
# import std           .stdio ;
#
# struct Foo {
#   int[] alpha = [0, 1, 2],
#         beta  = [3, 4, 5];
# }
#
# void main () {
#   Foo foo ;
#
#   writefln("foo.alpha == ", foo.alpha);
#   writefln("foo.beta  == ", foo.beta );
#
#   foo.alpha.drop(1U);
#
#   writefln("foo.alpha == ", foo.alpha);
#   writefln("foo.beta  == ", foo.beta );
# }

For me this output:
foo.alpha == [0,1,2]
foo.beta  == [3,4,5]
foo.alpha == [0,2]
foo.beta  == [3,4,5]

Which seems to imply the data after alpha isn't being touched.  That said, I'll try 
changing it anyhow.  Just in case.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list