Class Arrays need to be allocated
Monkey Forums/Monkey Programming/Class Arrays need to be allocated
| ||
I couldn't find any reference to this subject, but never really thought why this is so:Class Other Field x:Int End Local a:Other[] = New Other[10] a[5].x = 10 ''segmentation error but yet it's ok with built-in types. Question 2: is there an easy way to allocate object arrays? I assume not and we have to allocate object arrays in a for/next loop. doing a = a[0..10] does not work either. |
| ||
you need to initialize(create) each object. this is actually good because it won't use up memory unless you create the individual objects and makes arrays quite flexible.Class Other Field x:int End Local a:Other[] = New Other[10] ' allocate pointers for 10 objects For Local i:int = 0 until 10 Other[i] = new Other ' assign new object to pointer next a[5].x = 10 I am sure you can think of a way to automate it for your needs. |
| ||
right, automate it with the class:Class Other Field x:Int Function AllocateArray:Other[](i:Int=0) Local o:Other[i] For Local j:= 0 To i-1 o[j] = New Other Next Return o End End But I guess my assumption that the memory was allocated, looking at the resulting cpp code: Array<bb_androidtest_Other* > t_a=Array<bb_androidtest_Other* >(10); And the Array cpp class does a memset in the constructor.... or so I think. This is why I question why it gives me a seg fault? EDIT: I would have assumed this allocates pointers: Local a:Other[10] ...and this would allocate object memory: Local a:Other[] = New Other[10] |
| ||
I have always thought of "New Object[n]" as a way to create a new array size. I am not too familiar with cpp but if it creates arrays like c than it's handling the objects in the same way Monkey is. |
| ||
a = a[0..10] does not work either. If you want to resize an array try array.Resize( x )... not sure if thats what you mean |
| ||
I would have assumed this allocates pointers: Local a:Other[10] ...and this would allocate object memory: Local a:Other[] = New Other[10] These are essentially the same thing. Instantiating an array only creates the space for the pointers. You still need to instantiate each object and assign them to the array indices. |
| ||
In C++, an instance of Other would basically be an int, and New Other[10] would return a pointer to an array of ten ints. In Monkey, Other is an object that contains an int. In other words the array of Others consists of ten pointers to instances of Other objects. The pointers aren't valid until the objects are allocated. |