Basic Rookie question (pass array to a function)

Hi there,

My head is exploding with the step from arduino to c++ in PLatformio but Im enjoying it at the same time

I have this fucntion:

void loadSong(byte songno) {
 byte songx[]={};

if (songno==2) songx[]=song2[];
if (songno==3) songx[]=song3[];
if (songno==4) songx[]=song4[];
if (songno==5) songx[]=song5[];

  for (byte j = 0; j <= 254; j++) {
    opl2.setRegister(j, songx[j]);

Obviously, what I want is to receive an int or byte and depending of the number of the byte, pass a different array to that function, but for the nails of Christ that I can´t find the appropiate syntax.

Can anyone hints?


When you assign variables of any type (integral type, pointer or array), you just assign var1 = var2; and never put [] after the variable (unless of course you want to dereference it, like var1 = var2[some_index]; or you need a cast first)

I think what you meant to do is have a byte* which points to the 255-byte long song, but depending on the song number the songx pointer points to a different song. So something like

void loadSong(byte songno) {
	byte* songx = nullptr;

	if (songno==2) songx = (byte*) song2;
	else if (songno==3) songx = (byte*) song3;
	else if (songno==4) songx = (byte*) song4;
	else if (songno==5) songx = (byte*) song5;
	else { 
		//error: unknown song.
		Serial.println("Unknown song number: " + String(songno));

	for (byte j = 0; j <= 254; j++) {
		opl2.setRegister(j, songx[j]);

The (byte*) cast is for the case that song2 is defined as a byte array of known size, and GCC will complain when you assign this array to a simple pointer variable. But it’s perfectly valid here. You can also write &song2[0] to get a byte* to the start of the song :wink:

Yeah!! It works first time!! Thank you so much!!

I dont understand pointers yet but you got it lightning fast. Thank you, gonna study this :slight_smile: