How to pass array to function in Arduino

How to pass an array to a function in Arduino?

Answer

There are two ways to pass array to a function on Arduino

Pass Array to a Function by Array Type

Example code

void myFunction(int myArray[], int length) { for (byte i = 0; i < length; i++) { Serial.println(myArray[i]); } Serial.println(); // add an empty line } int array_1[2] = {1, 2}; int array_2[4] = {1, 2, 3, 4}; void setup() { Serial.begin(9600); myFunction(array_1, 2); myFunction(array_2, 4); } void loop() { }

The output on Serial Monitor:

COM6
Send
1 2 1 2 3 4
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Pass Array to a Function by Pointer Type

Example code

void myFunction(int *myPointer, int length) { for (byte i = 0; i < length; i++) { Serial.println(*(myPointer + i)); } Serial.println(); // add an empty line } int array_1[2] = {1, 2}; int array_2[4] = {1, 2, 3, 4}; void setup() { Serial.begin(9600); int pointer_1 = &array_1; int pointer_2 = &array_2; myFunction(pointer_1, 2); // pass via a pointer myFunction(pointer_2, 4); // pass via a pointer } void loop() { }

The output on Serial Monitor:

COM6
Send
1 2 1 2 3 4
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

See Array reference

Buy Arduino

1 × Arduino UNO Buy on Amazon
1 × USB 2.0 cable type A/B Buy on Amazon
1 × Jumper Wires Buy on Amazon
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.

The Best Arduino Starter Kit

※ OUR MESSAGES