[fpc-pascal] Why use pointers to arrays?
Florian Klaempfl
florian at freepascal.org
Sun Oct 11 10:44:16 CEST 2009
Graeme Geldenhuys schrieb:
>
>
> 1) Why would you use a pointer to an array and not simply a variable
> what IS the array? In the program I am porting the following field
> variable is defined.
>
> FLines: ^TLinesArray;
>
> Why couldn't I simply say:
>
> FLines: TLinesArray;
Because this array has a fixed size.
>
> Is there some advantage for using a pointer to the array, when passing
> it around between procedures and functions?
>
>
> 2) The TLinesArray is a dynamic array, so shouldn't I maybe change the
> ported code to define the array as follows, instead of the [0..0]
> idea?
>
> TLinesArray = array of TLayoutLine;
A dynamic array does several magic behind your neck mainly taking care
of managed types. It depends on the code if it works or not.
>
>
>
> 3) Maybe the strange usage (to me at least) of dynamic arrays could be
> explain in how the original program allocates memory for the array. In
> the class where FLines is defined, it initially reserves ten empty
> elements for the array in the class constructor.
>
> FAllocatedNumLines := 10;
> GetMem( FLines, FAllocatedNumLines * sizeof( TLayoutLine ) );
>
> And then later if it needs more space for elements, it redefines the
> array elements as follows:
>
> Procedure TRichTextLayout.AddLineStart( Const Line: TLayoutLine );
> var
> NewAllocation: longint;
> begin
> if FNumLines >= FAllocatedNumLines then
> begin
> // reallocate the array twice the size
> NewAllocation := FAllocatedNumLines * 2;
> FLines := ReAllocMem(FLines, NewAllocation * sizeof(TLayoutLine));
> FAllocatedNumLines := NewAllocation;
> end;
> FLines^[ FNumLines ] := Line; // ***** (1)
> inc( FNumLines );
> end;
>
>
> Like I said, maybe this is related to different implementations of
> object pascal. By doesn't one allocate memory (array elements) via the
> SetLength() procedure?
SetLength is a Borland extension. The code as shown is standard pascal
code. It's relative complexity simply shows why dyn. arrays were invented.
More information about the fpc-pascal
mailing list