Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

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

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: "Incompatible types".

Should I stick to the for-loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...