Arrays of types?

BlitzMax Forums/BlitzMax Programming/Arrays of types?

ImaginaryHuman(Posted 2005) [#1]
Hey folks.

I was designing some software and wondering what would be the best way to keep track of a whole list of objects, with easy adding and removing of objects - ie the memory is allocated on a per-object basis. I figured I had two options - linked lists or arrays. But then it hit me, there is a third cool and useful possibility with BlitzMax - an array of custom types.

For example

Type mytype
   a:Int
   b:Int
   c:Int
   d:Int
   e:Int
End Type

Local myarray:mytype[50]
Print SizeOf(myarray) 'prints 50*4 bytes per index = 200
'At this point you have an array but it's an array of Null pointers and doesn't take up any extra memory than to hold the pointers

myarray[20]=New mytype
myarray[20].a=123
myarray[20].b=456
myarray[20].c=789
myarray[20].d=101
myarray[20].e=112
Print myarray[20].a+myarray[20].b+myarray[20].c+myarray[20].d+myarray[20].e
'Prints the content of the new type
Print sizeof(myarray) 'Still prints 200 as the size of the array
Print sizeof(myarray[20]) 'Prints the size of the type instance =20

I think this is pretty cool because you can add and remove `link` by adding instances of a custom type, which allocates and deallocates memory as needed, while also giving you an array index that keeps them all in order and lets you jump to a specific numbered entry if you need to.

Of course you can't so easily remove a link like in a linked list, but you can `free up` a link by releasing the instance of the custom type, and then when you want to add a new link you can just search through the array for a null pointer. Obviously the array, in general, is a fixed size, but you can still resize it if you want to and it will only need to deal with copying the pointers to each type (or null's) rather than the entire content.

I figured a nice quick(ish) way to do the search for an empty slot is to keep track of a `NextFreeIndex` variable which you increment each time you add a new type instance, and when you reach the end of the array you just loop around to the start. Then you just do a loop that searches from the `next` index through the whole array like in a circle, to find the next free slot. It *should* find a new empty slot pretty soon.

I think it's a nice combination of both linked-list functionality and array convenience. I just wanted to share the joy. BlitzMax is cool!