Arduino Return Array from Function
As Arduino boards are programmed using C/C++ language so both these languages do not allow returning an array to a function as an argument. However, we can return an array from a function by specifying the array’s name without any index.
We must declare a function returning a pointer if we want to return a one-dimensional array from the function. Second point to remember is that the C language does not allow local variables to return addresses outside the function, so local variables should be declared as static to avoid any compilation error.
Description
While programming Arduino boards we can initialize an array having a particular size, once the array is initialized its value can be replaced using a function. Dynamic memory allocation is required when we want to return an array which is initialized inside a function. To do this malloc() and free() functions can be used along with pointers in Arduino.
The problem is if a function returns an array using dynamic memory allocation the result may be changed due to memory leakage and dangling pointers. So the best way of returning an array from a function is to initialize an array and change its values using a function instead of returning the whole array from the function.
Let’s create a function to change the values of an array by initializing it with a constant integer size. See the code below.
Example Code
int Array_New[size]; /*New Array is defined*/
void Array() /*Function to store arrays value*/
{
for (int i=0;i<5;i++) /*for loop to store values in function*/
{
Array_New[i]=i;
}
}
void setup()
{
Serial.begin(9600); /*Serial Communication begins*/
Array(); /*Array function is called*/
for (int i=0;i<size;i++)
{
Serial.println (Array_New[i]); /*Array elements are printed*/
}
}
void loop() {
}
In the above code, an array is initialized using constant integers because if we don’t use a constant integer, IDE will show an error. Here in the given array, we have not stored any values so the array will be initialized with null values but we can also store values inside the array during initialization.
Next we created the Array() function having return type void to store values inside the array. Also, the return type is void because we don’t want to return anything we only need to store values, in case if one needs to return value, we can change return type according to them such as int.
Next for loop is used to store values however we can also store values manually. After that using Serial.print() output is printed on the serial monitor.
Output
Output print values from 0 to 4 returning an array from a function:
Conclusion
This article covers up all the detailed steps on how we can initialize an array using the constant integer data type and store value inside it using the for loop. Later the Array() function is called inside the setup part of code hence resulting in returning Array from function.