有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。


当前回答

您可以使用sizeof()操作符,该操作符用于相同的目的。

请参阅下面的示例代码

#include <iostream>
using namespace std;
int main() {
  int arr[] = {10,20,30,40,50,60};
  int arrSize = sizeof(arr)/sizeof(arr[0]);
  cout << "The size of the array is: " << arrSize;
  return 0;
}

其他回答

如果你指的是c风格的数组,那么你可以这样做:

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;

这对指针不起作用(即它对以下任何一个都不起作用):

int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;

or:

void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);

在c++中,如果你想要这种行为,那么你应该使用容器类;可能std::向量。

有没有办法找出一个数组有多少个值?

Yes!

尝试sizeof(数组)/ sizeof(阵列[0])

检测是否已经到达数组的末尾也可以工作。

我看不到任何方法,除非你的数组是一个字符数组(即字符串)。

注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。

我在这里提供了一个棘手的解决方案:

你总是可以在第一个元素中存储长度:

// malloc/new

arr[0] = length;
arr++;

// do anything. 
int len = *(arr-1);

free(--arr); 

代价是在调用free时必须—arr

使用泛型的一个好的解决方案:

template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }

然后简单地调用arraysize(_Array);来获取数组的长度。

下面是谷歌Protobuf中ArraySize的一个实现。

#define GOOGLE_ARRAYSIZE(a) \
  ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;

ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling. Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t. This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.