Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of items in a byte array

Tags:

c++

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 array?

like image 582
Alon Gubkin Avatar asked Dec 03 '22 13:12

Alon Gubkin


1 Answers

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
}
like image 100
interjay Avatar answered Dec 25 '22 17:12

interjay