I’m having a problem that might not be too common. I have several arrays and I want to reference each array with a char. However, I get the error message “invalid types ‘char[int]’ for array subscript”.
int a[] = {0, 1};
int b[] = {1, 2};
char letter = 'a';
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(letter[1]);
}
Looks like the OP thinks having “letter” set to ‘a’ will access elements in array “a”.
Having letter set to ‘b’ will access elements in array “b”.
C/C++ is a compiled language. You can not access/modify variable names at runtime.
int a[] = {0, 1};
int b[] = {1, 2};
int* arrays [] = { a, b };
char letter = 'a';
if (letter >= 'a' && letter <= 'b')
{
Serial.print(arrays[letter-'a'][1]);
}
Edit: Note the above ONLY works because the array names as sequential and consecutive letters (because of letter-‘a’).
Also, if all the arrays are the same length, you might do better with a 2 dimensional array.
pcbbc:
Looks like the OP thinks having “letter” set to ‘a’ will access elements in array “a”.
Having letter set to ‘b’ will access elements in array “b”.
C/C++ is a compiled language. You can not access/modify variable names at runtime.
int a[] = {0, 1};
int b = {1, 2};
int* arrays = { a, b };
char letter = ‘a’;
if (letter >= ‘a’ && letter <= ‘b’)
{
Serial.print(arrays[letter-‘a’][1]);
}
Edit: Note the above ONLY works because the array names as sequential and consecutive letters (because of letter-'a').
Also, if all the arrays are the same length, you might do better with a 2 dimensional array.
You are right, that was what I hoped to achieve. However, as you have pointed out it doesn’t seem to be allowed in the C language. I tried your suggestion but ended up circumventing my problem with a switch case. Thank you for your suggestion!