开发者

Number of items in a byte array

开发者 https://www.devze.com 2022-12-16 09:28 出处:网络
I\'ve the following C++ array: byte data[] = {0xc7, 0x05, 0x04, 0x11 ,0x45, 0x00, 0x00, 0x00, 0x00, 0x00};

I've the following C++ array:

byte data[] = {0xc7, 0x05, 0x04, 0x11 ,0x45, 0x00, 0x00, 0x00, 0x00, 0x00};

How can I know how many items there are in this 开发者_如何学Carray?


For byte-sized elements, you can use sizeof(data).

More generally, sizeof(data)/sizeof(data[0]) will give the number of elements.


Since this issue came up in your last question, I'll clarify that this can't be used when you pass an array to a function as a parameter:

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
}


You should really use Neil's suggestion: std::vector<byte> is a much better solution in most cases (the only more complex part is initialization, on anything else it is safer).

If not, instead of using the sizeof(array)/sizeof(array[0]), or sizeof(array) (since sizeof(byte)==1), you can use a typesafe approach with templates:

template <typename T, unsigned int N>
unsigned int size_of_array( T (&)[N] ) {
   return N;
}

Or, if you need a compile time constant (and at the same time you want to make sure you do not accidentally call it on non-arrays:

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))))

In most cases you will not need that last solution. Both templated solutions will fail fast when a pointer is passed (instead of an array):

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!!!
}


sizeof( data);     // because sizeof(byte) is 1

However, this is not a good general solution - particularly if you pass the array to functions:

void  f( byte a[] ) {
   // number of elements in 'a' unknown here 
}

The array decays to a pointer, so the sizeof operator will always give you the size of the pointer, not the number of elements in the array.

Instead, you should use a std::vector<byte>, which has a size() member function.

0

精彩评论

暂无评论...
验证码 换一张
取 消