Products > Programming
Query the compiler to determine how many elements in const String array
(1/1)
ornea:
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: ---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"}
};
--- End code ---
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: ---byte buttonStates[8][2] = {
{0, 6},
{0, 2},
{0, 4},
{0, 2},
{0, 3},
{0, 2},
{0, 1},
{0, 1}
};
--- End code ---
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
greenpossum:
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.
magic:
--- Quote from: ornea on April 13, 2020, 04:39:12 am ---something like this would be nice
int n0 = sizeof(strButtonStates[0])
but it always returns 12
--- End quote ---
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.
Navigation
[0] Message Index
Go to full version