Problem
Create a dynamic array of objects of equal type;
E.g. strings, structs.
The array should occupy no more memory than required to store the objects.
Method
Define an Array class which manages a list of untyped (void) pointers.
The Array class declares a pointer to untyped pointer, as the base of the array.
The constructor must allocate the memory occupied by the bsase pointer (to pointer).
A counter property is declared within the Array class to track the number of objects within the array.
The array is zero based, with the counter equivalent to UBound +1.
The object to be added to the array must be allocated before being handed to the array class Add method.
The Add method Reallocates the list of pointers.
The new object pointer is assigned as the last member of the pointer list and the counter incremented.
A Del(ete) method is defined to remove objects from the list by index number.
The delete method shifts pointers within the list [index -1], reallocates the list and finally frees the object which was removed.
The class destructor frees any objects remaining in the array before freeing the base pointer.
[code]
class dynamicArray {
private: void** _elements; uint16 _count;
public: dynamicArray(void); ~dynamicArray(void);
void* get(uint16); void add(void* newElement); void del(uint16);
}
//constructor dynamicArray::dynamicArray {
_elements = (void**) malloc(sizeof(void*)); _recordCount = 0;}
//destructor dynamicArray::~dynamicArray (void) {
for (i = _count; i > 0; i--) {
free( _elements[i]);
} free(_elements); _count = 0
//add element void dynamicArray::add( void* newElement) {
void** elements = _elements; _elements = (void**) realloc( _elements, (_count+1) * sizeof(void*));
if (_elements == NULL) { //out of memory, restore the list _elements = elements; } else { _elements[_count++] = newElement; } }//delete membervoid dynamicArray::del(uint16 index) { if (index >= _count) { return; } void* elementToDelete = get(index); if (elementToDelete != NULL) { for (uint16 i = index; i < _count; i++) { _elements[i] = elements[i +1]; } _elements = (void**) realloc(_elements (--count) * sizeof(void*)); free(elementToDelete;} //get elementvoid* dynamicArray::get(uint16 index) { void* element = NULL; if (index < count) { element = _elements[index]; } return element;} // example use//global declarationdynamicArray MyArray;void loop(void) { char* aString; for (uint i = 0; i < 4; i++) { aString = (char*) malloc(17 * sizeof(char)); sprintf(aString, "Line %02d", i); MyArray.add(aString); } MyArray.del(2); for (uint i = 0; i < MyArray.Count(); i++) { Serial << (char*) MyArray.get(i); } //local object dynamicArray* myarray = new dynamicArray; myarray->add("a string literal"); Serial << myarry->get(1) << "\n"; delete myarray} [/code]
« Go back
Powered by Help Desk Software HESK, in partnership with SysAid Technologies