C++ - Passing a C-style array with size information to a function
Posted on November 28, 2016 by Paul
When you pass a C-style array to a function it will decay to a pointer to the first element of the array, basically losing the size information.
As a side note, in a pure C++ code, one will prefer to use std::vector or std::array instead of C-style arrays. However, there are cases like in embedded systems in which using the Standard Template Library is forbidden by your company guide rules or simply not available on the platform. This is why I think the approach presented in this article could be of some interest to C++ programmers.
In C, you will need to pass the size of the array as an extra parameter to the function or use a global variable. A potential problem with this approach is that it is easy to screw up by forgetting the array to pointer decay rule or by passing the wrong size information.
Here is an example of a classical bug when one forgets about the array to pointer decay rule:
As mentioned before, a better version is to pass the array information to the function:
A problem with the above approach is that nothing prevents you from passing the wrong size information to the function, e.g:
A potential solution, for the C language, to the above problem is to use a macro that will always put the correct size of the array, something like:
You can obviously avoid the pointer decay problem if you use a global variable, however this is considered a bad practice so we won’t discuss it here.
If you are using C++ there is a better approach, you can pass the array as a reference to the function, this way you will keep the size information:
Similarly, you can pass a multi-dimensional C-style array to a function without losing the size information:
If you are interested to learn more about modern C++ I would recommend reading A Tour of C++ by Bjarne Stroustrup.