get the length of an object array


I have some troubles to get a length of a object array.
I have made a class for defining pin outputs and with an array i store the instances of the class.
Now i have something like:

DigitalPin leds[6] = {led1, led2, led3, led4, led5, led6};

If i try to loop trough the array with a for loop and an argument of sizeof(leds) the output gives 18

for(int i = 0; i < sizeof(leds); i++){

Does somebody know how to solve this problem?
If there is no solution i will try to make a new class with a classmethod to get the size of an array,
but if there is a class available i like to know that of course.

That is normal. The “sizeof()” returns you the size in bytes and not the “number of elements”. you must do something like:

#define MAX_LEDS 6

DigitalPin leds[MAX_LEDS ] = {led1, led2, led3, led4, led5, led6};


for(int i = 0; i < MAX_LEDS; i++){

A more portable, typeless, way to do it is:

#define ARRAYSIZE(x)  (sizeof(x) / sizeof(x[0]))

//  ...more code...

  for (i = 0; i < ARRAYSIZE(leds); i++) {
      // Rest of code...

This macro works with any array, regardless of whether it’s an int, char, float, etc. The way it works is, if you define an int array as:

int myArray[3];

The sizeof(myArray) returns 6, since that is the number of bytes allocated to the array. However, divide that by myArray[0], which is 2 bytes for each int element in the array, you get 6/2 = 3, which is the proper element count. Note that this works regardless of data type. Also note that, if you change the number of elements in the array initializer list, you do not have to edit the macro…it self-adjusts.

But do not worry about the division slowing things down. since all the sizes are known at compile time, the compiler does the division and supplies the value as a constant.

If you want a fancy way to get the data and array size, you can use a template. (For Functions)

T in the data type of the array, (byte, int, long…)
N is the arrays size.

template<typename T, size_t N> 
T sort(T (&Arr)[N]) // returns the sorted array with the same data type
  for (int i = N - 1; i > 0; i--)
    for (int j = 0; j < i; j++) 
      if (Arr[ j ] > Arr[ j + 1 ]) 
        T Temp = Arr[ j ]; // create new variable with the same data type.
        Arr[ j ] = Arr[ j + 1 ];
        Arr[ j + 1 ] = Temp;