Arduino Return Array From Function

This tutorial will discuss returning an array from a function by modifying an existing array in Arduino.

Arduino Return Array From Function

In Arduino, we can initialize an array with a given size; after initializing an array, we can add or replace values of the array using a function.

Array in JavaScript || Full-Stack W...
Array in JavaScript || Full-Stack Web-Development Course #24

If we want to initialize and create an array inside a function and then return it when the function is called, we have to use the dynamic memory allocation, which is done using the malloc() and free() functions, and we also have to use the pointers in Arduino.

The problem is if we create and return an array from a function using dynamic memory allocation, the result might change because of memory leakage and dangling pointers. So, it is best to initialize an array and change its values using a function rather than returning a whole array from a function.

For example, let’s initialize an array with a constant integer size and then create a function to change the array values. See the code below.

const int size = 10;
int MyArray[size];

void CreateArray()
{
 for (int i=0;i<size;i++)
  {
   MyArray[i]=i;
  }
}

void setup()
{
  Serial.begin(9600);
  CreateArray();
  for (int i=0;i<size;i++)
  {
    Serial.println (MyArray[i]);
  }
}
void loop()
{

}

Output:

0
1
2
3
4
5
6
7
8
9

In the above code, we initialized the array using a constant integer because we have to use a constant integer to initialize an array, and if we don’t use a constant integer, Arduino will show an error. We have not stored any values in the array, but we can also store values when we initialize an array.

If we don’t store any values in an array, the array will be initialized with NULL values. We created the CreateArray() function to store values in the array.

The CreateArray() return type is void, meaning we don’t want to return anything because we only want to store values in the array. We can change the return type if we want to return something; like, if we want to return an integer value, we can define the int return type.

We used a for loop to store values inside the array, but we can also manually store values inside the array. We called the CreateArray() function inside the setup() function to change the array’s values before we use it to print them.

We used the serial monitor of Arduino to print the values of the array, and as we can see in the output, ten values are present in the array.

Related Article - Arduino Function

  • Arduino sscanf Function
  • Generate Random Numbers in Arduino
  • Arduino millis() Function