有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。
在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)
其他回答
Sizeof (array_name)给出整个数组的大小,Sizeof (int)给出每个数组元素的数据类型的大小。
所以用整个数组的大小除以数组中单个元素的大小就得到了数组的长度。
int array_name[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(array_name)/sizeof(int);
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
而不是使用内置的数组函数aka:
int x[3] = {0, 1, 2};
您应该使用数组类和数组模板。试一试:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
现在如果你想求数组的长度,你所要做的就是使用数组类中的size函数。
Name_of_Array.size();
这应该返回数组中元素的长度。
下面是谷歌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.
对于旧的g++编译器,您可以这样做
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}