3

I'm trying to make a use of a relay module, I want a clear way to configure and control my relay module I've defined the struct and filled it with some info about id, pin number, title, and relay state I can't loop with for in the array of controls, because I can't get the sizeof the array right

typedef struct{
  int id;
  int pin;
  String title;
  bool state;
}  SwitchControl;

SwitchControl controls[2] = { {1, 22, "Switch 01", 1}, {2, 23, "Switch 02", 0}, };

for(int i=0; i<sizeof(controls) - 1; i++){ }

thanks

ocrdu
  • 1,795
  • 3
  • 12
  • 24
Moktar
  • 31
  • 1
  • 2

3 Answers3

3

To make it generic, you simply divide the sizeof the array by the sizeof the type:

for(int i=0; i<sizeof(controls)/sizeof(SwitchControl); i++){
}

Then you can later change the items if the array, or the structure and the code will be the same.

Eugenio Pace
  • 296
  • 1
  • 10
2

A more generic way (usable in future cases) is:

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

Now you can use ARRAY_SIZE (the_array) in your code like this:

for(int i=0; i<ARRAY_SIZE (controls); i++){
}

The above works in C as well as C++.


The more C++ way of doing it is to use a template like this:

// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

Now ArraySize(the_array) returns the number of elements in the array:

for(int i=0; i< ArraySize (controls); i++){
}

The "Arduino language" is C++ with some initial pre-processing. For all intents and purposes any tutorial on C++ will help you with Arduino programming (except that the Standard Template Library (STL) is not included by default).


I don't know why you were subtracting 1 in your posted code. Did you not want to iterate through the whole array?

Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
0

sizeof(controls) returns the size, in bytes, of the entire object which is not what you want. You want the number of elements.

I'll point out that since you're statically allocating this as:

SwitchControl controls[2]

The size you are looking for is always going to be 2. So just use 2 in your for loop like:

for(int i=0; i<2; i++)

jwh20
  • 1,045
  • 5
  • 8