Is there way of copying the whole array into another array? (Other than using a For-loop)

前端 未结 6 1349
孤街浪徒
孤街浪徒 2020-12-14 23:40

Is there way of copying the whole array into another array? Other than using a for-loop.

Does the move or copy command work for this? I did try but it had an error:

6条回答
  •  执念已碎
    2020-12-14 23:59

    To be on the safe side, use the Copy function on dynamic arrays, as it handles the managed types internally. The arrays must be of the same type, i.e. declared in the same expression:

    var  
        a, b: array of string;
    

    or by defining a custom array type:

    type   
        TStringArray = array of string;  
    var 
        a: TStringArray;  
    //...and somewhere else
    var  
        b: TStringArray;  
    

    then you can do:

    a := Copy(b, Low(b), Length(b));  //really clean, but unnecessary 
    //...or   
    a := Copy(b, 0, MaxInt);  //dynamic arrays always have zero low bound 
                              //and Copy copies only "up to" Count items  
    

    You'll have to use a loop on static arrays and when mixing array types (not that I'd recommend doing it).
    If you really have to use Move, remember checking for zero-length, as the A[0] constructs can raise range checking errors, (with the notable exception of SizeOf(A[0]), which is handled by compiler magic and never actually executes).
    Also never assume that A = A[0] or SizeOf(A) = Length(A) * SizeOf(A[0]), as this is true only for static arrays and it will bite you really badly if you later try to refactor huge codebase to dynamic arrays.

提交回复
热议问题