[Solved] Array of structs or pointer indexing ... Options / Best practice?

Dyslexicbloke:
I don't see how Nicks code achieves that whilst the pointers do.

Yes, I skimmed. Sometimes a rewrite is better. I rewrite my own stuff when I get bogged down. I didn't comment everything because I find comments like this annoying:

  Serial.begin (115200);   // start serial comms at 115200 baud

Those comments don't add anything to the code IMHO.


The essence of my suggestion was in this array:

xVar vals [] = {
  { "BatVolts",  BatVolts },
  { "ACVolts",   ACVolts },
  { "WindSpeed", WindSpeed },
  { "PVCurrent", PVCurrent },
};

That ties each name (eg. "BatVolts") to a reference to the variable. The variable is not in the array, a reference is. A reference is a fancy C++ way of doing pointers (in effect) without actually have to use the * and & operators, so it is easy to use.

This lets you (as I demonstrated in the code) change the original values, eg.

BatVolts = 22;

The reference in the array now "points to" (can I say "refers to"?) the same original variable.

So if someone using the serial port wants to know the "BatVolts" value (by name) you simply scan the array with a simple "for" loop, looking for a string match, and then reply with the variable which is referenced (as I demonstrated with the printing).