Tutorial Study Image

Passing array to a function in C++


September 4, 2022, Learn eTutorial
1289

In this tutorial, we will demonstrate using examples how to pass a single-dimensional as well as a multidimensional array as a function parameter in C++. In C++, arrays can be passed mainly as arguments to functions. Furthermore, functions can return arrays. Make sure you understand C++ Arrays as well as C++ Functions before learning about passing arrays as function arguments.

What exactly do you mean by passing an array to a function?

  • Arrays can be passed as arguments to functions in the same way that variables can. Furthermore, functions can return arrays.
  • To pass an array to a function, simply mention the array name during the function call.
  • Make sure you understand C++ Arrays and C++ Functions before learning about passing arrays as function arguments. For better understanding check out our previous tutorials.

Syntax

The syntax for mainly passing an array to a function in C++


returnType functionName(dataType arrayName[arraySize]) {
// statement
}
 

For an example


int total(int num[4]) {
// statement
}
 

In this case, we've passed an int type array labeled num to the function total (). The array has a size = 4.

Function declaration that uses an array as a parameter

There are two methods that might be used to do this: call by reference as well as call by value.

  1. Either a parameter can be an array.
    
    int sum(int arr[]);
     
    
  2.  Alternately, a pointer to our array's base address can be kept in the argument list.
    
    int sum(int* ptr);
     
    

Example for Passing a Single Array mainly to a Function

Let's create a very basic program in which the main() function declares and defines an array of integers, and each member of the array is sent to a function that only prints the value of an element.


// Displaying a single array element using C++
#include <iostream>
using namespace std;
void arr(int a ) {
    // just display the array elements
        cout << "Numbers " << a <<endl;
}

int main() {
    // here we should declare as well as  initialize an array
    int myArr[] = {11, 12, 13};
    arr(myArr[1]); //just pass the array element myArr[1] only.

    return 0;
}

Output:

Numbers 12

An example of passing the one-dimensional array to a function with an explanation


// C++ Program to display roll numbers of 6 students
#include <iostream>
using namespace std;

// declare function in order to display the Roll Number & take a 1d array as parameter
void display(int a[6]) {
    cout << "Display The Roll Numbers: " << endl;

    // display array elements
    for (int i = 0; i < 6; ++i) {
        cout << "Student " << i + 1 << ": " << a[i] << endl;
    }
}
int main() {
    // declare and initialize an array
    int rollNum[6] = {41, 11, 73, 32,67,100};
    
    display(rollNum);    // call display function pass array as argument

    return 0;
}

Output:

Display The Roll Numbers: 
Student 1: 41
Student 2: 11
Student 3: 73
Student 4: 32
Student 5: 67
Student 6: 100

Let us see the working of the above program

  1. Only the array name is used when calling a function mainly by passing an array as an argument.
    
    void display(int m[6])
     
    

    The memory address of the very first element of the array rollNum[6] is represented by the parameter rollNum in this case.

  2. Take note of the display() function's parameter.
    
    display(rollNum);
     
    

    In this case, we use the entire array declaration in the function parameter, which also includes the square braces [].

  3. int m[6] is converted to int* m by the function parameter. This will be pointing to the same address that the array marks pointed to. As a result, whenever we alter m[6] in the function body, we are essentially altering the original array marks. This is how C++ manages to provide an array to a function to conserve memory and time.

Why the whole contents of an array cannot be passed as an argument to a function in C++?

The whole contents of an array cannot be passed as an argument to a function in C++. The array name alone, without an index, allows you to supply a pointer to an array.

You can declare a function's formal parameter in one of the following three methods to pass a single-dimension array as an argument. All three declaration procedures yield equivalent results because they each inform the compiler that an integer pointer will be received.

  1. Method  1: The formal parameters as a pointer are as follows:
    void myFunction(int *param) {
    .
    .
    .
    }
     
    
  2. Method  2: The formal parameters as a sized array are as follows:
    void myFunction(int param[20]) {
    .
    .
    .
    }
    
  3. Method  3: The formal parameters as an unsized array are as follows:
    void myFunction(int param[]) {
    .
    .
    .
    }
    

Now think about the function below, which will accept an array as an input along with another argument. Mainly based on the passed arguments, it will return the average of the numbers passed via the array as follows.


double getAverage(int arr[], int size) {
  int i, sum = 0;       
  double avg;          

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }
   avg = double(sum) / size;

   return avg;
}
 

Next, let us call the preceding function exactly as follows:


#include <iostream>
using namespace std;
 
// function declaration:
double getAverage(int arr[], int size);

int main () {
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;
 
   // output the returned value 
   cout << "Average value is: " << avg << endl; 
    
   return 0;
}

Output:

Average value is: 214.4

As you can see, the method doesn't care how long the array is because C++ doesn't conduct any bounds checks on the formal parameters.

An example of passing the multi-dimensional array to a function with an explanation.


#include <iostream>
using namespace std;

// just define a function 
// pass a 2 dimensional  array as a parameter
void display(int n[][3]) {
    cout << " The Displaying Values: " << endl;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 3; ++j) {
            cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
        }
    }
}

int main() {

    // initialize 2d array
    int num[4][3] = {
        {8, 4},
        {9, 3},
        {5, 1}
    };

    // call the function
    // pass a 2d array as an argument
    display(num);

    return 0;
}

Output:

The Displaying Values: 
num[0][0]: 8
num[0][1]: 4
num[0][2]: 0
num[1][0]: 9
num[1][1]: 3
num[1][2]: 0
num[2][0]: 5
num[2][1]: 1
num[2][2]: 0
num[3][0]: 0
num[3][1]: 0
num[3][2]: 0

A function called display() has been defined in the program mentioned above. The function will be taking a two-dimensional array. It takes an argument of int n[][3] and outputs the contents which means the elements of the array.

We only pass the two-dimensional array's name as the function argument display when calling the function (arr).

Array Returning from a Function in C++

  • Functions return a pointer that contains the base address of the array to be returned rather than an array itself.
  • However, we must ensure that the array continues to exist after the function ends, meaning it cannot be local to the function.
  • The function also has the option of returning an array. The real array, however, is not given back or returned.
  • Instead, pointers are used to return the address of the array's first element.