Array creation and passing on function

Is there a way to create an array while passing it as a value into a function?

I mean something like

callMyFunctionThatAcceptsAnArray({0x00, 0x02, 0x03});

Also is there a way to get its size without running a for counter?

Unfortunantly, tha answer is 'no' to both questions.

This is the shortest way:

void setup(){
byte array[] = {1,2,3};
function( array, 3 );
}
void loop(){
}
void function( byte arr[] , byte length){
for (byte i=0; i<length; i++){
//do something with arr*[/color]*

  • }*
    }
    [/quote]

Actually you can pass it, and calculate the size of it using sizeof().

sizeof() returns the size of a variable or type. sizeof(char) should be 1. sizeof(int[2]) should be 8 in the AVR, and sizeof(short) should be 2. Each is the bytes it takes to hold the variable.

In the following example, sizeof(buffer) is 512. If you know it is a char, you don't need to divide by sizeof(char) - which is 1 in this case (char). I put it in there to show how to calculate the members in an array of any kind (int, float, etc...) where the size of each array member isn't always 1.

int buffer[512];

void setup()
{
     int iElements = sizeof(buffer)/sizeof(int); // equals 512/1 = 512.
     func(buffer);
}

void func(int *theBuffer)
{
   // can't use sizeof(theBuffer) here.  It would be the size of a int*, not what you pass in.
   i = (thebuffer)[1];

}

Remember though that sizeof isn't dynamic - the compiler figures it out for you at compile time. As a result, the following example won't work, because the definition of the function doesn't tell the compiler how big the array 'theBuffer' can be at execution: (I don't even think it will compile!)

This won't work:

void setup(){
  byte array[] = {1,2,3};
  function( array );
}
void loop(){
}
void function( byte arr[] )
{
  for (byte i=0; i<(sizeof(arr)/sizeof(byte)); i++){
    //do something with arr[i]
  }
}

this will:

void setup()
{
    int array[] = {1,2,3};
    function(array, sizeof(array)/sizeof(int));
}
void function( int arr[], int len )
{
  for (byte i=0; i<len; i++){
    //do something with arr[i]
  }
}

(I think) it is much safer to have a const variable keeping track of the array size. That way you can safely pass arrays to objects and functions.

const byte ARRAY_SIZE = 100;
byte array[ARRAY_SIZE] = {0};

Although this is subject to personal preference, I also think it is safe to say this:

If you make it a habit of always keeping track of the array length, you will be bothered with a lot less bugs.