[Solved] Finding Length of an Array [duplicate]


When arrays are passed into functions, they undergo array-to-pointer conversion. This means an array of type T[N] will simply decay into T*. Notice how the size information has been lost. All that remains is a pointer to the first element of the array. Here is a quote from the Standard:

4.2 Array-to-pointer conversion

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue
of type “pointer to T”. The result is a pointer to the first element of the array.

In short, sizeof( array ) returns the size of the pointer, not of the array. That’s where the miscalculation derives. A simple solution would be to utilize dynamic containers like std::vector which contains its size information internally:

#include <vector>

void myFunction(std::vector<int> const &array)
{
    int size = array.size();
}

If using std::vector isn’t an option, you can use a reference to an array instead while using a template argument to deduce the length:

template <unsigned N>
void myFunction(int (&array)[N])
{
    int size = N;
}

8

solved Finding Length of an Array [duplicate]