Append an element to a C-style array
C-style arrays might be tricky. Even such a trivial task like appending an element might surprise you. It actually surprised me a few times. I do not use raw array in day-to-day programming, I always prefer vector or std::array if I need a fixed size container, but this is just an educational purpose to see the logic when appending an item. It is one of the basics algorithms.
Having an array of these parameters.
constexpr size_t capacity{ 20 };
int arr[capacity] = { 3,1,5,1,6,1,2,1,6 };
size_t length = 9;
How do we append an element?
First, we need to check if there is space for the new element. Something I used to forget to do. That means if the length is smaller than capacity. If so, we can append a new element. Where to append? To the one-past last index, which is represented by length.
if (length < capacity) { arr[length] = elem; }
Here is the whole function
void append(int* arr, size_t &length, int elem)
{
if (length < capacity)
{
arr[length] = elem;
}
else
{
throw std::out_of_range("No space to append element");
}
++length;
}
If there is space, we append, if not, we throw an exception. The important thing is, that we have to increment the length of the array after we append, so that is why we pass length by reference and increment it inside the function.