Array length with pointers

arrays, c++, pointers

Solution

You cannot. A pointer is just a memory location, and contains nothing special that could determine the size.

Since this is C++, what you can do is pass the array by reference like so:

template <typename T, size_t N>
void handle_array(T (&pX)[N])
{
    // the size is N

    pX[0] = /* blah */;
    // ...
    pX[N - 1] = /* blah */;
}

// for a specific type:
template <size_t N>
void handle_array(int (const &pX)[N]) // const this time, for fun
{
    // the size is N

    int i = pX[0]; // etc
}

But otherwise you need to pass start & end and do a subtraction, like Alok suggests, a start & size, like you suggest, or ditch a static array and use a vector, like Tyler suggests.

If you know the size of the array you'll be working with, you can make a `typedef`:

typedef int int_array[10];

void handle_ten_ints(int_array& pX)
{
    // size must be 10
}

And just for the size:

template <typename T, size_t N>
size_t countof(T (&pX)[N])
{
    return N;
}

template <typename T, size_t N>
T* endof(T (&pX)[N])
{
    return &pX[0] + N;
}

// use
int someArray[] = {1, 2, 6, 2, 8, 1, 3, 3, 7};

size_t count = countof(someArray); // 9
std::for_each(someArray, endof(someArray), /* ... */);

I use these utility functions from time to time.

Problem

How in C++ get array length with pointers only ? I know that tab name is pointer to first element, but what next ?

Original source