I'm seeing some confusing behavior with a 2D Array I've created in Flash (using the PROGMEM attribute). First, some code:
// Macro to perform "sizeof" on PROGMEM Arrays
#define ELEM_CNT(x) (sizeof(x) / sizeof(x[0]))
// Individual Arrays
const byte a0[] PROGMEM = {0, 0, 1, 2, 3, 4, 5, 6};
const byte a1[] PROGMEM = {0, 0, 9, 8, 7, 6, 5, 4};
const byte a2[] PROGMEM = {0, 0, 5, 6, 7, 8, 9, 0};
// Array of arrays
const byte *arrays[] PROGMEM = {
a0,
a1,
a2,
};
byte i,j;
for (i = 0; i < ELEM_CNT(arrays); i++)
{
Serial.print("Array #");
Serial.print(i, DEC);
Serial.print(": ");
for (j=0; j<8; j++)
{
Serial.print(pgm_read_byte(&(array[i][j])), DEC);
Serial.print(" ");
}
Serial.println();
}
Like this, I get gibberish in the serial output, like this:
Array #0: 0 0 251 193 0 0 249 193
Array #1: 2 3 4 5 6 1 2 3
Array #2: 2 3 4 5 6 1 2 3
But if I make one change, things work great...
// snippet from above with modification
for (i = 0; i < ELEM_CNT(arrays); i++)
{
Serial.print("Array #");
Serial.print(i, DEC);
Serial.print(": ");
for (j=0; j<8; j++)
{
if (i == 0)
Serial.print(pgm_read_byte(&(array[i][j])), DEC);
Serial.print(" ");
}
Serial.println();
}
Output:
Array #0: 0 0 1 2 3 4 5 6
Array #1:
Array #2:
Now with this, I get the expected output, with the obvious caveat of it only works for one case, which defeats the entire purpose of trying to make a 2D array in the first place. Alternatively, I can just hardcode in a value for the first index (i) of the array and it works great, but as soon as I try to iterate over more than one index, it doesn't work. I'm confuse by it because I don't see any obvious errors, especially since it works with a hardcoded value, but this is my first foray into the PROGMEM attribute, so I could just be missing something frustratingly obvious. Any ideas?
Thanks!