Passing Array to Function in Arduino
Arduino programming doesn’t allow directly passing an entire array as argument of function. However, a pointer can be passed to an array by specifying its name.
To pass single dimension arrays as a function argument we must consider following three given syntax. All three will output the same result and tell the IDE that a pointer is coming.
Syntax 1: A pointer with formal parameters.
Syntax 2: A pointer with a sized array.
Syntax 3: A pointer with an unsized array.
We can pass array to Arduino function using two different methods:
Pass Array by Array Type
Now in this method we will pass an array to a function as an argument of that function. Let’s take an example to understand how to pass an array to a function.
Example Code
Serial.println("Printing Array Elements: ");
for (int i = 0; i < 5; ++i) { /*For loop to print array elements*/
Serial.print("Element ");
Serial.print(i+1); /*Condition to increase element number every time code run*/
Serial.print(": ");
Serial.println(num[i]); /*Element number is printed*/
}
}
void setup() {
Serial.begin(9600); /*Serial communication begins*/
int num[5] = {10, 20, 30, 40, 50}; /*Array elements with sized initialized*/
display(num); /*Array elements displayed*/
return 0;
}
void loop() {
}
In above code first a new function with void return type is initialized with an array size of 5. For loop is printed to return numbers from 1 to 5 every time code runs. Notice the parameters of void display() function here we used full declaration including array size and function parameters along with square braces[ ].
In the loop part using display(num) we call the original function by passing an array as an argument. Here num represents the first element memory address.
Output
Output window shows the elements of the array one by one. Using a for loop all the 5 elements of array are passed to function.
Conclusion
Arduino programming like C++ doesn’t allow passing an entire array to a function, however using a pointer to an array by specifying the name of the given array we can easily pass any array elements to a function completely. Three different syntax are followed to pass an array to function. This writeup will assist you to pass any array to function inside the Arduino sketch.