Stange behaviour of open arrays: bis
Original Reporter info from Mantis: SimBen
-
Reporter name:
Original Reporter info from Mantis: SimBen
- Reporter name:
Description:
Sorry to insist, in the link http://rvelthuis.de/articles/articles-openarr.html
it is written
procedure OnlyDyn(Arr: TMonthArray);
Procedure OnlyDyn will only accept dynamic arrays, so you can use SetLength here (this will however use a copy, and not change the original array; if you want to change the length of the original array, use var Arr: TMonthArray in the declaration).
The following program so erroneously writes 7 instead of 6. Indeed, the original array being passed by value (there is no var in front of A) and therefore should not be modified in the main program, because bobo is assumed to work on a copy of X.
type T=array of byte;
var x: T;
Procedure bobo(A: T);
begin inc(A[1]); end;
BEGIN
setlength(x,2); x[1]:=6;
bobo(x); writeln(x[1]);
END.
The problem certainly comes from the fact that a copy of a dynamic array is linked to it, so that changes to the copy affect both the copy and the original array. It seems that a simple way to de-link them is to use the setlength procecure. Thus the following modified program correctly writes 6:
type T=array of byte;
var x: T;
Procedure bobo(A: T);
begin setlength(A,2); inc(A[1]); end;
BEGIN
setlength(x,2); x[1]:=6;
bobo(x); writeln(x[1]);
END.
If the compiler cannot be changed to automatically de-link the copy and the original dynamic array when passed to a routine by value, at least the doc should mention this issue.
Mantis conversion info:
- Mantis ID: 19207
- OS: Windows
- OS Build: XP SP3
- Platform: PC
- Version: 2.4.2