Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada: Array length modification when adding anew element

I try to create a dynamic array package. I have a generic package with a generic type and then I have declared in .ads an array (Positive indexes) of elements Elem_Type. I was curious if it is possible to create a procedure Append(Vector, Item) where to modify Vector's length, allowing him to take one more element. Something like when you have a buffer[100] in C and allocate him 1 more element to make it 101 then add something on position 101.

like image 685
Daniel Constantinescu Avatar asked Dec 23 '22 23:12

Daniel Constantinescu


1 Answers

In Ada the general way to do this is to create a new and bigger block, then copy the contents to it and free the old block. I often suggest allocating new blocks in multiples of some large chunk size so you don't have to reallocate much. So like if you have to allocate a new array, instead of adding just one extra element, add 500 (or some number that makes sense).

Note that even in C, the realloc() function often does exactly this. It isn't common in non trivial projects for the realloc() function to be able to actually just add another element. It often times has to create an entire new array and do the copy, just like I am suggesting for Ada.

Some other options in Ada include making your own storage pool that makes reallocating a lot easier and faster, but you have to come up with the algorithm on how to do that or find someone elses. You can also do bindings to the C functions, but you cannot mix malloc/realloc/free with Ada's new/unchecked_deallocation

like image 154
Jere Avatar answered Jan 13 '23 22:01

Jere