I have an array declared as:
const A: array[0..3] of ShortString = (
'Customer',
'Supplier',
'Stock',
'GL'
);
var B: array of ShortString;
I would like to clone the string array A to another array B. Using Move or Copy function doesn't work. Is there a fast and easy way to clone the array without using for loop?
The problem you face is that your constant A and your variable B are actually of different types. This can be demonstrated most easily by showing how you would declare a const and a var of the same type in a fashion equivalent to what you show in your question:
type
TSA = array[0..3] of ShortString;
const
A: TSA = (
'Customer',
'Supplier',
'Stock',
'GL');
var B: TSA;
With these declarations you could then simply write:
B := A;
But when A is a dimensioned array and B is a dynamic array, this isn't possible and your only option is to SetLength(B) as required and copy the elements one-by-one.
Although the const and the var types may look like they are the same - or compatible types - they are not, and this then is no different from trying to assign an Integer constant to a String variable... even though you know the simple conversion required to achieve it, the compiler cannot presume to guess that you intended this, so you have to be explicit and provide the conversion code yourself.
Something like:
SetLength(B, Length(A));
for i := Low(A) to High(A) do
B[i] := A[i];
Or in a more generic way:
type
TStringArray = array of ShortString;
procedure CloneArray(const source: array of ShortString; var dest: TStringArray);
var
i: integer;
begin
SetLength(dest, Length(source));
for i := Low(source) to High(source) do
dest[i] := source[i];
end;
In the latter case you'll have to redeclare B as B: TStringArray.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With