带指针的数组长度 [英] Array length with pointers
问题描述
在C ++中如何仅使用指针获取数组长度?我知道选项卡名称是指向第一个元素的指针,但是下一个是什么?
How in C++ get array length with pointers only ? I know that tab name is pointer to first element, but what next ?
推荐答案
您不能.指针只是一个内存位置,不包含任何可以确定大小的特殊内容.
You cannot. A pointer is just a memory location, and contains nothing special that could determine the size.
由于这是C ++,所以您可以做的是像这样通过引用传递数组:
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
}
但是,否则您需要通过启动&结束并进行减法运算(如Alok建议的那样),即开始与大小,如您建议的那样,或者抛弃静态数组并使用矢量,如Tyler建议的那样.
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.
如果知道要使用的数组的大小,则可以创建typedef
:
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.
这篇关于带指针的数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!