[Gambas-user] arrays
Tobias Boege
taboege at gmail.com
Sun Apr 21 05:01:40 CEST 2019
On Sun, 21 Apr 2019, Shane wrote:
> I have coded this
>
> At the beginning of the main module i declare
>
> public s[100] as point {point is a class with x as integer and y as integer
> and thats all}
>
> so I go to use the array
>
> s2.SetPosition(s[i].x * size, s[i].y * size)
>
> but i get an error null object
>
> the array side works i get 100 arrays of NULL
>
> now do i make the elements accessible?
>
> I was expecting to have 100 elements of x=0 and y=0
>
> can someone enlighten me please thanks
>
If you create an array of type X with N elements, you're allocating space
to store N elements of type X, nothing more. Creating an array will not
automatically create objects that go into the array for you (auto-vivifying,
as its called in other languages). The array is filled with Null, which
explains the error you get. It's *not* filled with usable objects whose
properties are zero. In short: you have to initialize the array yourself:
For i As Integer = 0 To 99
s[i] = New Point
Next
And by the way, "s[100] As Point" will create a so-called embedded array
which has several drawbacks [1]. It's mostly useful when you need to be
certain about the memory layout of the array, like when interfacing with
external libraries. Use "s As New Point[100]" instead, which creates a
normal array of predefined size.
Regards,
Tobi
[1] http://gambaswiki.org/wiki/cat/arraydecl
--
"There's an old saying: Don't change anything... ever!" -- Mr. Monk
More information about the User
mailing list