Board index » delphi » Record Type and Dynamic Arrays

Record Type and Dynamic Arrays

Hi,
  Sorry if I am posting to the wrong group.  I am running in to a problem
and I am hoping someone can help:
Basically, I am created a record type and want to assign it to a dynamic
array then by getting a record count set the array length.

For example
Type TAnimal = record
  typ: string
  legs: Integer;
  brothers: Array of string;
end;

var dogs: array of TAnimal

I later ...

SetLength(dog,1);
...
i := 1;
With .. Do begin ...
  While NOT EOF Do Begin
    Dog[i].type := 'Mutt';
    inc(i);  Setlength(dog,i);
    end{While};
  end{With...};

All this works but when I assign something to Dog[i] it bombs.  What can I
do?

Thank you,
Christopher

 

Re:Record Type and Dynamic Arrays


Dynamic arrays are 0-based, not 1-based.  When you say SetLength(Dogs,1) the
first element is Dogs[0].

Thus you always set the length to the actual number of elements (n) that you
want, then reference 0 to n-1.

Quote
"Christopher Anglin" <Dovest...@erols.com> wrote in message

news:3b5732d4_1@dnews...
Quote
> Hi,
>   Sorry if I am posting to the wrong group.  I am running in to a problem
> and I am hoping someone can help:
> Basically, I am created a record type and want to assign it to a dynamic
> array then by getting a record count set the array length.

> For example
> Type TAnimal = record
>   typ: string
>   legs: Integer;
>   brothers: Array of string;
> end;

> var dogs: array of TAnimal

> I later ...

> SetLength(dog,1);
> ...
> i := 1;
> With .. Do begin ...
>   While NOT EOF Do Begin
>     Dog[i].type := 'Mutt';
>     inc(i);  Setlength(dog,i);
>     end{While};
>   end{With...};

> All this works but when I assign something to Dog[i] it bombs.  What can I
> do?

> Thank you,
> Christopher

Re:Record Type and Dynamic Arrays


Quote
> i := 1;
>     Dog[i].type := 'Mutt';
> All this works but when I assign something to Dog[i] it bombs.  What can I
> do?

This would go in delphi.objectpascal.

Your problem is that dynamic arrays are 0-based.

Other Threads