[Lazarus] Passing a section of an array to a function.

Sven Barth pascaldragon at googlemail.com
Mon Sep 10 10:14:06 CEST 2012


Am 10.09.2012 08:36, schrieb Dave Coventry:
> Hi,
>
> I have an array of Byte which I have loaded from a file.
>
> I want to process a 100 byte section of the array which starts at
> offset 32 in my array.
>
> My function (or procedure) is as follows:
>
> procedure decompress_r(cbuf: array of byte);
> var
>    len,i: integer;
> begin
>    i:=1;
>    if (cbuf[0]and $F0)=$20 then
>    begin
>      Inc(i,2);
>      len:=cbuf[i]and $7;
>    end;
>    ...
> end;
>
> I call my procedure by
>
> decompress_r(&buf[32]);

Did you really write "&"? The address operator is "@", but this won't 
make your code work anyway. If you did indeed write "&" (which is for 
escaping keywords) you do indeed only pass the 32nd element to your 
function.

>
> It seems to work. the first element in the array is 0x20, but the rest
> of the array is garbage.
>
> The array sent is:
> buf[32]=32
> buf[33]=0
> buf[34]=0
> buf[35]=7
> buf[36]=0
>
> The array received is
> cbuf[0]=32
> cbuf[1]=27
> cbuf[2]=255
> cbuf[3]=247
> cbuf[4]=255
>
> Can anyone tell me the correct way to pass the portion of the array to
> the function?

Dynamic arrays are internally pointers to an array (more or less). So if 
you would use "@buf[32]" you would be passing the address of one element 
to a function that takes an array. If you know the amount of bytes you 
want to copy then you should use "Copy(buf, 32, count)" as argument for 
decompress_r or if you don't know the amount you should change your 
function from "array of Byte" to "PByte" and pass the address of the 
32nd byte using "@buf[32]". The remaining part of the function can stay 
the same.

Regards,
Sven




More information about the Lazarus mailing list