lokki i guess i will need to use pointers instead in the array pattern?
yes that could work:
byte a[8] = {60,62,63,65,67,68,71,72};
byte* b[4] = {&a[0], &a[2], &a[4], &a[6]};
then you'd access values of b
and dereference them (note the *
:
byte myvar = *b[3];
*b[2] = 25;
// now a[4] == 25
(this could be made a bit nicer using an array of references instead of an array of pointers)
In your case above, however, you are also doing some operations on the values of a
. Unfortunately this won't work:
byte a[8] = {60,62,63,65,67,68,71,72};
byte* b[4] = {&a[0], &a[2] + 12, &a[4] + 24, &a[6]};
(I mean, it compiles, but it doesn't give you what you want, as those +
are actually between a pointer and an integer, look up "pointer arithmetics" if you are interested in knowing why this doesn't do what you'd want it to).
So if you want these mathematical operations to be reflected in b
when you change an element in a
, you can only do this by using a dedicated class that takes care of this.
For instance, a toy example:
class FluidArrays {
private:
byte a[8] = {60,62,63,65,67,68,71,72};
byte bIdx[4] = {0, 2, 4, 6};
byte bOffset[4] = {0, 0, 12, 24};
public:
byte& getA(size_t idx) { return a[idx]; }
byte getB(size_t idx) { return a[bIdx[idx]] + bOffset[idx]; }
};
note that getA()
returns a reference therefore you can both read and write to it. getB()
doesn't (and couldn't, because of the maths applied to the array element). So you can do
FluidArrays f;
byte myVar = f.getA(3); // returns 65
myVar = g.getB(3); // returns 65+24 = 89
f.getA(3) = 40; // sets element
myVar = f.getA(3); // returns 40
myVar = f.getB(3); // returns 40+24 = 64
If you really wanted to, through the magic of operator overload and the addition of another class and a couple of methods, you could get creative and have a nicer syntax (without any *
or get..()
) and have something as magic (and confusing?) as this, which is probably closer to what you had in mind:
FluidArrays a;
ReadableArray b = a.getB();
byte myVar = a[3]; // returns 65
myVar = b[3]; // returns 65+24 = 89
a[3] = 40; // sets element
myVar = a[3]; // returns 40
myVar = b[3]; // returns 40+24 = 64