Selecting item from array of char arrays in Arduino

Viewed 139

I'm trying to write a function to play a random track from a predefined list of tracks from an Adafuit board connected to an Arduino Nano by serial. I've put the list of tracks in an array of char arrays and am having difficulty getting it to select an item from the array.

char T00[20] = "T00     OGG";
char T01[20] = "T01     OGG";
char T02[20] = "T02     OGG";
char T03[20] = "T03     OGG";
    
char rndTracks[] = {T00,T01,T02,T03};

int l = sizeof(rndTracks) - 1;
int r = random(l);
Serial.println(rndTracks[r]);
char trk[20] = rndTracks[r];
Serial.println(trk);
if (!sfx.playTrack(trk) {
  Serial.println("Failed to play track?");
}

This is the error:

error: array must be initialized with a brace-enclosed initializer   
char trk[20] = rndTracks[r];

Any ideas?

1 Answers

Here you seem to be trying to copy a string/array by assigning it.

char trk[20] = rndTracks[r];

That does not work with C-like arrays of char.

Numerous ways exist to do the copying you try. E.g. using C++ strings, or strncpy()...

But what you probably really want to do is to simply skip the copying and just output via reference to the randomly selected array of char.

Either directly:

Serial.println(rndTracks[r]);

Or, if you need to for some reason (e.g. convenience of the following line),
via a variable, which simply stores the selected pointer:

char* trk = rndTracks[r];
Related