我有以下C++数组:
byte data[] = {0xc7, 0x05, 0x04, 0x11 ,0x45, 0x00, 0x00, 0x00, 0x00, 0x00};
Run Code Online (Sandbox Code Playgroud)
我怎么知道这个数组中有多少项?
对于字节大小的元素,您可以使用sizeof(data).
更一般地说,sizeof(data)/sizeof(data[0])将给出元素的数量.
由于您的上一个问题出现了这个问题,我将澄清当您将数组作为参数传递给函数时,不能使用此问题:
void f(byte arr[])
{
//This always prints the size of a pointer, regardless of number of elements.
cout << sizeof(arr);
}
void g()
{
byte data[] = {0xc7, 0x05, 0x04, 0x11 ,0x45, 0x00, 0x00, 0x00, 0x00, 0x00};
cout << sizeof(data); //prints 10
}
Run Code Online (Sandbox Code Playgroud)
你应该真正使用Neil的建议:std::vector<byte>在大多数情况下,这是一个更好的解决方案(唯一更复杂的部分是初始化,其他任何事情都更安全).
如果没有,您可以使用带有模板的类型安全方法,而不是使用sizeof(array)/sizeof(array[0])或sizeof(array)(自sizeof(byte)==1).
template <typename T, unsigned int N>
unsigned int size_of_array( T (&)[N] ) {
return N;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要编译时常量(同时您希望确保不会在非数组上意外调用它:
template <typename T, unsigned int N>
char (&static_size_of_array( T (&)[N] ))[N];
#define compile_time_size(x) (sizeof(static_size_of_array((x))))
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,您不需要最后的解决方案.传递指针(而不是数组)时,两个模板化解决方案都会快速失败:
void f( char array[] ) // misleading name:
{
char array2[] = { 1, 2, 3 };
size_of_array(array2); // 3
size_of_array(array); // compile time error
sizeof(array)/sizeof(array[0]); // 4/8, depending on architecture!!!
}
Run Code Online (Sandbox Code Playgroud)