Icon View Thread

The following is the text of the current message along with any replies.
Messages 1 to 4 of 4 total
Thread SetLength in Arrays
Mon, Dec 30 2013 10:34 AMPermanent Link

Uli Becker

Hi,

I am using an array (MovieList of TMovie).

Surprisingly this code works without exception:

  SetLength(MovieList,0);
  NewMovie := TMovie.create;
   try
      NewMovie.title := 'test0';
      MovieList[0] := NewMovie;
   finally
      NewMovie.free;
   end;

   NewMovie := TMovie.create;
   try
      NewMovie.title := 'test1';
      MovieList[1] := NewMovie;
   finally
      NewMovie.free;
   end;

I expected an error here because the length of the array was set to 0.
Does that mean that I don't have to change the length of the array?

Thanks Uli
Mon, Dec 30 2013 10:59 AMPermanent Link

Raul

Team Elevate Team Elevate

On 12/30/2013 10:34 AM, Uli Becker wrote:
> I expected an error here because the length of the array was set to 0.
> Does that mean that I don't have to change the length of the array?
>

As per manual you DO need to set the length or get a run-time error so
either manual is incorrect or EWB compiler is not checking the array
bounds properly.

After doing setting length 0 and assigning elements 0 and 1 as you did
the Length function does return 2 so array is getting updated.

Raul
Mon, Dec 30 2013 11:45 AMPermanent Link

Uli Becker

Raul,

> After doing setting length 0 and assigning elements 0 and 1 as you did
> the Length function does return 2 so array is getting updated.

thanks for confirming that.

Uli
Mon, Jan 6 2014 1:15 PMPermanent Link

Tim Young [Elevate Software]

Elevate Software, Inc.

Avatar

Email timyoung@elevatesoft.com

Uli,

<< I expected an error here because the length of the array was set to 0.
Does that mean that I don't have to change the length of the array? >>

Technically, no, but you have to realize *why* this is the case.  You're
calling SetLength() on the array, which causes the array to be created
properly.  If you didn't do so, then you would get an error.  So, while you
don't have to set the length specifically, you do have to set the length to
*something*, so I would promptly ignore what you just learned and keep
coding in the same way that you do with native Delphi code.   It will save
you a lot of headaches.

Tim Young
Elevate Software
www.elevatesoft.com
Image