I'd like to know if anyone could point me out to what would be the difference when using the two different copy approaches for array, which is defined as type.
I needed to make a function that would order the elements of integers in dynamic array, from either min to max or max to min. Therefore, I created a new type like this:
type IntArray = array of integer;
Then I defined a function to sort, with two directions, which are identified by integer passed, with parameter being 0 to sort towards minimum (max -> min) or 1 to sort towards max (min -> max).
function SortArray(ToSort: IntArray; Direction: integer): IntArray;
var count, i: integer;
Label Label1, Label2;
begin
count:=Length(ToSort);
if (Direction = 1) then
begin
Label1:
for i := 0 to count-2 do
begin
if ToSort[i+1] > ToSort[i] then
begin
ToSort[i+1] :=ToSort[i] +ToSort[i+1];
ToSort[i] :=ToSort[i+1] -ToSort[i];
ToSort[i+1] :=ToSort[i+1] -ToSort[i];
GoTo Label1;
end;
end;
end
else
if (Direction = 0) then
begin
Label2:
for i := 0 to count-2 do
begin
if ToSort[i+1] < ToSort[i] then
begin
ToSort[i+1] :=ToSort[i] +ToSort[i+1];
ToSort[i] :=ToSort[i+1] -ToSort[i];
ToSort[i+1] :=ToSort[i+1] -ToSort[i];
GoTo Label2;
end;
end;
end;
Result:=ToSort;
Now, this function works fine as it seems, however the result differs regarding how I define the arrays that are passed to the function call;
I have an OnClick event for a button, which gives two calls of the function:
procedure Button1Click(Sender: TObject);
var a, b: IntArray;
i: Integer;
begin
SetLength(a, 10);
SetLength(b, 10);
for i := 0 to 9 do
begin
a[i]:=Random(100);
b[i]:=a[i]; // Example 1;
end;
// b:=a; // Example 2;
a:=SortArray(a, 1);
b:=SortArray(b, 0);
for i := 0 to 9 do
begin
Listbox1.Items.Add(InttoStr(a[i]));
Listbox2.Items.Add(InttoStr(b[i]));
end;
end;
Now the thing is, if I define array B the way it is provided with example 1, -> the function works fine. A is sorted towards maximum, while B is sorted towards minimum;
However, if I define array B the way it is provided with example 2, -> the function gives me the same result for both calls, both being arrays sorted towards maximum (as called in the first call).
Why does it make a difference how I define array b, and why shouldn't I copy it directly as var to var? Doesn't seem to make much sense to me at this point...
TArray<Integer>is the dyn array of integer. Also, delphi already comes with sorting functions.