Author Topic: Query the compiler to determine how many elements in const String array  (Read 972 times)

0 Members and 1 Guest are viewing this topic.

Offline orneaTopic starter

  • Supporter
  • ****
  • Posts: 135
  • Country: au
Is it possible to query the compiler to determine how many elements in an const String array or do I need to manually count them.

In Arduino with a esp8266 target i declare this 2D const String array

Code: [Select]
const String strButtonStates[][10] {
  {"Jerky Dryer", "Yogurt Maker", "Egg Incubate", "Black Garlic", "Solder Reflow", "Solder Iron"},
  {"Toggle Scale °C", "Toggle Scale °F"},
  {"Run PID Loop", "Forced High", "Forced Low", "Forced MCV"},
  {"Active High", "Active Low"},
  {"Inject Water", "Auto Humidty", "Water Inhibit"},
  {"Active High", "Active Low"},
  {"Save State"},
  {"Reset Restart"}
};

I would like the compiler to tell me that there are 6 elements in the first array 2 in the second and so on.

something like this would be nice
 int n0 = sizeof(strButtonStates[0])

but it always returns 12

Perhaps there is a better way entirely that saves me having to define another array like this
Code: [Select]
byte buttonStates[8][2] = {
  {0, 6},
  {0, 2},
  {0, 4},
  {0, 2},
  {0, 3},
  {0, 2},
  {0, 1},
  {0, 1}
};

The first column records the current user selection, the second column records how many options there are for that button.

Any ideas or suggestions warmly welcome.

Ornea
 

Offline greenpossum

  • Frequent Contributor
  • **
  • Posts: 408
  • Country: au
I don't think so. The compiler doesn't provide a way for you to access that. If you are willing to use more names, you can do this:

const String choices1[] = {"Jerky Dryer", "Yogurt Maker", "Egg Incubate", "Black Garlic", "Solder Reflow", "Solder Iron"};
const String choices2[[ = {"Toggle Scale °C", "Toggle Scale °F"};
...

then you can write:

const String *strButtonStates[] = {
   choices1,
   choices2,
...
};

and their respective lengths are (sizeof choices1/sizeof choices1[0]), etc.

More indirection and names but less waste of uninitialised elements.
« Last Edit: April 13, 2020, 11:06:18 am by greenpossum »
 

Offline magic

  • Super Contributor
  • ***
  • Posts: 6779
  • Country: pl
something like this would be nice
 int n0 = sizeof(strButtonStates[0])

but it always returns 12
That's surprising, it should return sizeof(String)*10. In fact, I just tried it (with std::string) on my system and got just that.

The reason is because each of the arrays is indeed 10 elements long and each element is a String object of fixed size. The Strings which aren't initialized end up containing NULL pointers or some similar dummy values inside, but they still exist.

A possible solution is to replace the arrays with std::vectors, if that's available on Arduino. These contain only the explicitly initialized elements and know their length.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf