Pointer to first dynamic array element (was: Re: [fpc-pascal] Correct use of var in function calls?)
Michael Müller
mueller_michael at alice-dsl.net
Sat Feb 5 12:47:53 CET 2011
Hi Bo!
Am 03.02.2011 um 22:53 schrieb Bo Berglund:
> function TSSCommBuf.Read(var Data: TByteArr): boolean; // <== ???
> begin
> Result := Read(@Data, SizeOf(Data)) = SizeOf(Data);
> end;
When using dynamic arrays @Data will not be the address of the first array element which is usually what you want in combination with Read(). Since the dynamic array stores its length at the beginning with @Data you would overwrite the length value too.
So you have to use @Data[0]. Since this works also for static arrays you can / should do it always this way. This makes it also much easier to switch later from a static to a dynamic array.
A further hint for another example from you: When looping through the array use
for I := Low(Data) to High(Data)
instead of Len := Length(Data) and looping to Len - 1. Let the compiler do defining this local variable and the calculation.
Regards
Michael
More information about the fpc-pascal
mailing list