[fpc-pascal] Dynamic arrays, yet another pitfall

Flávio Etrusco flavio.etrusco at gmail.com
Sun Feb 9 16:34:48 CET 2014


On Sun, Feb 9, 2014 at 12:34 PM, Jürgen Hestermann
<juergen.hestermann at gmx.de> wrote:
> (...)
> With the following declaration and code:
>
> -------------------
> var A,B: array of integer;
> ...
> SetLength(A,10);
> B := A;
> SetLength(B,20);
> -------------------
>
> both variables A and B point to the same array with 20 Elements.
> Changing A changes B and vice versa.
> But a slight modification
>
> -------------------
> SetLength(A,0);
> B := A;
> SetLength(B,20);
> -------------------
>
> makes both variables A and B totaly decoupled! Although B is still assigned
> to be the same as A each variable is now a separate array with individual
> lengths and elements. Variable A has the length 0 and variable B is of
> length 20. Changing the length for one of them does no longer change the
> length of the other. If someone thinks about dynamic arrays as black boxes
> without the need to know the details because they are handled in the
> background then he will certainly be baffled by this.
> (...)

In other words: dynamic arrays are like AnsiStrings without the
copy-on-write semantics. I'd certainly wish Borland copied the COW
semantics :-/

-Flávio



More information about the fpc-pascal mailing list