How in C++ get array length with pointers only ? I know that tab name is pointer to first element, but what next ?
4 Answers
You cannot do it. You need to pass the array length along with the array pointer, or you need to use a container object such as std::vector.
4 Comments
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.
3 Comments
typedef to create an array type, and accepting a reference to that, to eliminate the template, unless these methods are going to be in a header file and the array size actually varies (yet remaining compile-time deterministic).template<size_t> is nice with auto-sized int ary[] = {…}; but instantiation might be inconvenient/confusing and the benefit is little AFAIK unless the array is declared like that. Or user happens to be working with several fixed sizes.You mean something like:
int a[10];
int *start = a;
int *end = a + 10;
size_t n = end - start; /* pointers! :-) */
1 Comment
for (int* i = start; i != end; ++i).You can't, unless you know what the end pointer dereferences to. In the case of char arrays, it's a '\0', so you can loop until you read that character to figure out the length.
1 Comment
\0. Not every char array is a string.