Passing argument

Can anyone direct me to an example which shows how to pass an array form a subroutine to main void loop. Thanks.

This is one risky way of doing it:

byte array = {1,2,3,4};

byte* getArray(){ return &array[0]; }

void setup() {
Serial.begin(9600);
byte* arr = getArray();
for(byte i=0; i<4; i++){
Serial.println(*(arr+i));
}
}

void loop(){

}

Or, as far as I remember from my C/C++ days, pass a buffer and its size as the function arguments, something like this (not tested though):

byte array[] = {1, 2, 3, 4, 5};
int  arraySize = 5;

// copy the array elements to the given buffer;
// return the number of elements copied;
int getArray(byte* pBuffer, int bufferSize)
{
  int nRet = min(bufferSize, arraySize);
  for (int i=0; i<nRet; i++)
  {
    pBuffer[i] = array[i];
  }
  return nRet;
}


void callGetArray()
{
  // allocate a buffer;
  byte buffer[3]={0};
  // get array elements in this buffer;
  int howMany = getArray(buffer, 3);
  // should return 3;

  // allocate a second, larger, buffer;
  byte bufferBig[10]={0};
  // get array elements in this buffer;
  howMany = getArray(bufferBig, 10);
  // should return 5;
}

AlphaBeta, you may already be aware of this, but &array[0] and array are equivalent. The name of an array variable IS a pointer to its first element. That’s why foo[] and and foo[5] and foo* are interchangeable as argument types.

byte* getArray() { return array; }

Your recommended code returned the address of a global array, which is perfectly safe and not risky at all. If the array were allocated as a stack variable inside the getArray() function, that would be bad.

You can use this scheme to good effect in animation:

#define LOOP 8
#define IMAGE 8
static byte _special_frame[IMAGE] = { ... };
static byte _looping_frames[LOOP][IMAGE] = { ... };

byte* getBitmapData(int framenum)
{
    if (framenum < 0 || framenum >= LOOP)
        return _special_frame;
    return _looping_frames[framenum];
}

Thanks very much. I will try this and get back to you. I greatly appreciate the response.

AlphaBeta, you may already be aware of this, but &array[0] and array are equivalent.

Yes, I am aware, but I like to emphesize this for later viewing of my code. :) [And for potentional readers]

Your recommended code returned the address of a global array, which is perfectly safe and not risky at all.

My reason for saying it is risky is that you do not get any indication of the array length, and could easily go out of bounds. And I always presume that functions will be implemented in a class eventually :)

Your example uses defines for length, which eliminates the problem [at least at global scope]