Since you can only pass a pointer to an array - and not the array itself - as an argument to a function in C, the information regarding the length of the array is lost. While you can derrive the length with something like sizeof(arr) / sizeof(int)
, that is a run-time operation and quite ugly.
There are other data structures, such as std::vector, that solves this problem, but it comes with a lot of other aspects, such as dynamic memory allocation, that you might not be interested in.
This gist provides a super simple implementation of an array of a fixed size that is not dynamically allocated but has its length as a property. Just like a normal array, it allows indexed element read and write operations, but nothing more.
I find this data structure useful as a substitute for the traditional C array, but like all things in programming, this implementation comes with its own set of drawbacks. The most obvious is that you have to specify the size of the array as a part of its type, which becomes a pain. In practise, what ends up happening is that you tend to have to annotate all functions that accepts an Array with the most generic template form, just like the struct itself:
template<typename T, size_t size>
void my_func(Array<T, size> & arr) {
// ...
}
Also, because of how the operator[]
is overloaded (returning a reference, which allows for write operations) you cannot create a const Array and expect indexed element access to work.