In this tutorial, we will learn how to pass an array to a function in c++. We will keep it simple and show how to send an array to a function.
In C++, you can pass arrays to functions in several ways based on your use case: by pointer, by reference, or by value.
Passing by Pointer
When you pass an array to a function, you actually passing a pointer to the first element of the array. The size of the array is not passed so it is a good practice to pass the size as an additional parameter.
#include<iostream> using namespace std; void printArray(int* arr, int size){ for(int i=0;i<size;i++){ cout<<arr[i]<<" "; } cout<<endl; } int main(){ int arr[] = {1,2,3,4,5,6,7,8,9}; int size = 9; cout<<"Printing array elements:"<<endl; printArray(arr,size); // Passing array by pointer return 0; }
Output:
Printing array elements: 1 2 3 4 5 6 7 8 9
Passing by Reference
You can pass an entire array to a function by reference. Using this way you don’t need to pass the size of array size separately.
#include<iostream> using namespace std; void printArray(int (&arr)[6]){ // Pass array of size 6 by reference for(int i=0;i<6;i++){ cout<<arr[i]<<" "; } cout<<endl; } int main(){ int arr[] = {1,2,3,4,5,6}; cout<<"Array elements are:"<<endl; printArray(arr); return 0; }
Output
Array elements are: 1 2 3 4 5 6
Passing by Value
C++ does not support to pass an array by value directly. However, you can wrap an array in a class or struct to pass a copy of it.
#include <iostream> using namespace std; struct Array{ int arr[5]; }; void printArray(Array ar){ int size = sizeof(ar.arr)/sizeof(ar.arr[0]); // Calculating size for(int i=0;i<size;i++){ cout<<ar.arr[i]<<" "; // Printing elements } cout<<endl; } int main(){ Array ar; // Creating an instance of struct for(int i=0;i<5;i++){ ar.arr[i] = i+1; //Assigning values to array } cout<<"Array elements are:"<<endl; printArray(ar); return 0; }
Output:
Array elements are: 1 2 3 4 5
Explanation:
Here we are using the ‘Array’ struct, which contains integer array of size 5. In main function, we first create an instance of the struct, then assign values to the array and finally call ‘printArray’ function to display the elements.