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:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
1 2 1 2 3 4
Ln 11, Col 1
Arduino Uno on COM15
2

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:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
1 2 1 2 3 4
Ln 11, Col 1
Arduino Uno on COM15
2

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