Array length with pointers
How in C++ get array leng开发者_如何学Goth with pointers only ? I know that tab name is pointer to first element, but what next ?
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
.
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.
You mean something like:
int a[10];
int *start = a;
int *end = a + 10;
size_t n = end - start; /* pointers! :-) */
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.
精彩评论