array copy/ref question
Jesse Phillips
jessekphillips at gmail.com
Mon Aug 11 19:42:17 PDT 2008
On Mon, 11 Aug 2008 21:20:32 -0400, Brian Sturk wrote:
> Lars Ivar Igesund Wrote:
>
>> Brian Sturk wrote:
>>
>> > I'm trying to get a handle on the array assignment, slicing
>> > operations and am a little confused. The last copy gives me an
>> > "overlapping array copy".
>> > Both arrays have a length of 4. Is it that I cannot copy from one
>> > dynamic array to another (even if the same size)?
>>
>> It means you are trying to copy from the same memory you are copying to
>> - your arrays reference the same memory.
>
> Hi there,
>
> Thanks for the clarification, sounds like I need to do a memcpy to do a
> true copy.
>
> ~telengard
The problem is at the top of the program, this should give you the same
error:
main( string[] args )
{
int[] test = [ 1, 2, 3, 4 ];
int[] copy;
copy = test;
test[1] = 7;
writefln( "Ref: test[1] %d copy[1] %d", test[1], copy[1] );
assert( test[1] == 7 );
assert( copy[1] == 7 );
copy = test[];
test[1] = 9;
assert( test[1] == 9 );
assert( copy[1] == 9 );
writefln( "Alt ref syntax: test[1] %d copy[1] %d", test[1], copy[1] );
writefln( "%d %d", test.length, copy.length );
copy[] = test; /* Want to copy, get Error: overlapping array copy
*/ test[1] = 11;
assert( test[1] == 11 );
assert( copy[1] == 9 );
writefln( "Copy: test[1] %d copy[1] %d", test[1], copy[1] );
}
You created copy and told it to point to test, you would need to
initialize copy to its own memory.
main( string[] args )
{
int[] test = [ 1, 2, 3, 4 ];
int[] copy = new int[4];
copy[] = test;
test[1] = 11;
assert( test[1] == 11 );
assert( copy[1] == 2 );
writefln( "Copy: test[1] %d copy[1] %d", test[1], copy[1] );
}
More information about the Digitalmars-d
mailing list