The number of elements in the byte array

I have the following C ++ array:

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

How to find out the number of elements in this array?

+3
source share
3 answers

For byte size elements you can use sizeof(data).

In general, the sizeof(data)/sizeof(data[0])number of elements will be indicated.


Since this question arose in your last question, I will explain that it is impossible to use 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
}
+9
source

You really should use the Neil suggestion: std::vector<byte>- this is a much better solution in most cases (the only more difficult part is initialization, otherwise it is safer).

, 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;
}

, ( , -:

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

. ( ):

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!!!
}
+5
sizeof( data);     // because sizeof(byte) is 1

- :

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

The array splits into a pointer, so the operator sizeofwill always indicate the size of the pointer, not the number of elements in the array.

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

+2
source

Source: https://habr.com/ru/post/1728729/


All Articles