Reference array with char?

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]);
}

stranger_things_backup.ino (140 Bytes)

(deleted)

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!

seems awkward

results

func: 0 [0]  0
func: 0 [1]  1
func: 1 [0]  2
func: 1 [1]  3
func: 0 [2]  2
func: 0 [3]  3
func: 0 [4]  0
#include <stdio.h>

int arr [2][2] = {
    { 0, 1 },
    { 2, 3 },
};

void
func (char c, int i)  {
    printf ("%s: %c [%d]  %d\n", __func__, c, i, arr [c - '0'][i]);
}

int
main ()
{
    func ('0', 0);
    func ('0', 1);
    func ('1', 0);
    func ('1', 1);

    func ('0', 2);
    func ('0', 3);
    func ('0', 4);
}