array copy/ref question

Brian Sturk bsturk at comcast.net
Mon Aug 11 14:57:02 PDT 2008


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)?

If I'm reading the docs correctly the copy syntax is to have the lhs use the brackets.

Here is my program:

import std.stdio;

///////////////////////////////////

void
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] );
}

Output:

 ./test_ref
Ref: test[1] 7 copy[1] 7
Alt ref syntax: test[1] 9 copy[1] 9
4 4
Error: overlapping array copy



More information about the Digitalmars-d mailing list