I am unable to access elements of a 2D PROGMEM array from inside a loop. Please see the following example:
const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
const byte * const arr[] PROGMEM = {a1, a2, a3, a4};
void setup() {
Serial.begin(9600);
Serial.println(pgm_read_byte(&(arr[0][0])));
Serial.println(pgm_read_byte(&(arr[1][0])));
Serial.println(pgm_read_byte(&(arr[2][0])));
Serial.println(pgm_read_byte(&(arr[3][0])));
for (int i = 0; i < 4; i++) {
Serial.print(i);
Serial.print(":");
Serial.println(pgm_read_byte(&(arr[i][0])));
}
int j = 0;
Serial.println(pgm_read_byte(&(arr[j][0])));
j = 1;
Serial.println(pgm_read_byte(&(arr[j][0])));
j = 2;
Serial.println(pgm_read_byte(&(arr[j][0])));
j = 3;
Serial.println(pgm_read_byte(&(arr[j][0])));
}
void loop() {
}
The output is:
97
101
106
114
0:12
1:174
2:12
3:148
97
101
106
114
I verified and re-verified the syntax so many times. could not find anyone facing similar issue. I am at my wits end why it would not print correct values inside the loop. Any ideas?
EDIT: expected output is:
97
101
106
114
0:97
1:101
2:106
3:114
97
101
106
114
arr[1][0]
are replaced at compile time with the items value. they are not read from the array in runtime. even withj
with constant value the compiler evaluates it at compile time and replaces with the value