Passing Arrays to functions in C/C++

Passing Arrays to functions in C/C++
Passing Arrays to functions in C/C++

Introduction 

In functions, we’ve covered the two different types of invoking (or calling) – Call By Value (or Pass by value) and Call By Reference (or Pass by reference). If you are already familiar with these methods, you may proceed further.

Passing arrays to functions in C/C++ is tricky and interesting. Wanna know how? Let’s get started with Passing Arrays to functions in C/C++

Passing Arrays to functions in C/C++

Passing arrays to functions in C/C++ behaves somewhat differently. Let’s understand why? Recall how we used to pass the variables to the function. Similarly, we can pass the array elements. 

Let’s understand it with an example:-

Assume we have an integer array age[5].


Here, assume we need to pass the 3rd element from the age array. To access the 3rd element, we can write age[3].

Let’s assign it with some value:-

age[3] = 78;
void func(int element , int sum = 0){ }   // Receiving element declared as integer

main(){
   ---
   ---
   func( age[3] ) ;          //Passing the 3rd element only i.e., 78
}

If we want to pass the entire array, then there is an interesting fact. Arrays are often confused with pointer,i.e., the memory address of some element. 

When we write age or any array name, then it refers to the memory address of the first element.

When an entire array is passed as an argument to a function, only the array name is passed,i.e., the starting address of the array gets passed to the function and not the copy of the entire array. When you call a function with an array name, a pointer to the first element in the array is passed into the function.

In this example, 1000 is passing to the pointer a. In simple words, we can perform any operation with age using a pointer. However, we’ve used the full declaration of the array in the function parameter. The compiler automatically converts it into the *a.

There are three ways to declare a parameter that is to receive an array pointer:

Let’s have a look at them one by one:

First WayThe receiving parameter of the array may itself be declared as an array, as shown below:

Syntax:-

return_type function(type arrayname[SIZE])

C

// Program To find the array sum using function

#include<stdio.h>
int add(int array[5]){                   //Declaration with size
    int sum =0;
    for(int i=0;i<5;i++){
        sum += array[i];
    }
    return sum;
}
int main(){
    int arr[5] = {2, 3, 4, 5, 6};
    printf("Array sum is %d\n", add(arr)); // For passing array, only its name is passed as argument
    return 0;
}

OUTPUT

Array sum is 20

C++

// Program to find the array sum using function

#include<iostream>
using namespace std;
int add(int array[5]){ //Declaration with size
    int sum =0;
    for(int i=0;i<5;i++){
        sum += array[i];
    }
    return sum;
}
int main(){
    int arr[5] = {2, 3, 4, 5, 6};
    cout<<"Array Sum is "<<add(arr)<<endl; // For passing array, only its name is passed as argument
    return 0;
}

OUTPUT

Array sum is 20

Here, as you see, in the above example, even though the parameter array is declared as an int array of 5 elements, the compiler automatically converts it to an int pointer like this int *array. This is necessary because no parameter can actually receive an entire array. A pointer to an array gets passed when an array is passed to the function; thus, a pointer parameter can only receive it.

illustrative_image
Source

Second Way- The receiving parameters may be declared as an unsized array, as shown below:

Syntax:-

return_type function(type arrayname[ ])

C

// Program to find the minimum element

#include<stdio.h>

int findMin(int arr[] , int size){ // Receiving array base address and size
    int min = arr[0];
    for(int i =1; i<size;i++){
        if(min > arr[i]){
            min = arr[i];
        }
    }
    return min;
}
int main(){
    int arr[5] = {76 , 89 , 67 , 23 , 24};
    printf("The minimum element is %d\n ",findMin(arr , 5)); // Passing array with size
    return 0;
}

OUTPUT

The minimum element is  23

C++

// Program to find the minimum element

#include<iostream>
using namespace std;
int findMin(int arr[] , int size){ // Receiving  base address and size
    int min = arr[0];
    for(int i =1; i<size;i++){
        if(min > arr[i]){
            min = arr[i];
        }
    }
    return min;
}
int main(){
    int arr[5] = {76 , 89 , 67 , 23 , 24};
    cout<<"The minimum element is  "<<findMin(arr , 5)<<endl; // Passing array with size
    return 0;
}

OUTPUT

The minimum element is  23

Since the compiler converts an array declaration( informal parameters of a function) into an array pointer, the actual size of the array is irrelevant to the parameter.

Third Way- The receiving parameters can be declared as a pointer, as shown below:

Syntax:-

return_type function(type *arrayname) {}

C

//Program to reverse the array using function

#include <stdio.h>
void reverseArray(int *arr, int start, int end) //Receiving parameter declared as pointer
{
    while (start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}    
void printArray(int *arr, int size)
{
   for (int i = 0; i < size; i++)
       printf("%d ",arr[i]);
   
   printf("\n");
 
}

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
     
    int n = sizeof(arr) / sizeof(arr[0]); // calculating size of the array
 
    printArray(arr, n); // To print original array
    
    reverseArray(arr, 0, n-1); // Calling the function with array name, starting point and ending point
     
    printf("Reversed array is\n");
    
    printArray(arr, n);     // To print the Reversed array
     
    return 0;
}

OUTPUT

1 2 3 4 5 6 

Reversed array is

6 5 4 3 2 1

C++

//Program to reverse the array using function

#include <bits/stdc++.h>
using namespace std;
void reverseArray(int *arr, int start, int end) //Receiving parameter declared as pointer
{
    while (start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}    
void printArray(int *arr, int size)  // Array name Declared as a pointer
{
   for (int i = 0; i < size; i++)
       cout << arr[i] << " ";
 
   cout << endl;
}

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
     
    int n = sizeof(arr) / sizeof(arr[0]); // calculating size of the array
 
    printArray(arr, n); // To print original array
    
    reverseArray(arr, 0, n-1);    // Calling the function with array name, starting point and ending point
     
    cout << "Reversed array is" << endl;
    
    printArray(arr, n);     // To print the Reversed array
     
    return 0;
}

OUTPUT

1 2 3 4 5 6 

Reversed array is

6 5 4 3 2 1

This is allowed because a pointer receiving an array can be used as an array. The critical point is that arrays and pointers are very closely linked. However, A pointer to an array gets passed when they are two different things and are generally not equivalent. The only exception is for function arguments, but this is only because function arguments can never be arrays- they are always converted to pointers.

Passing multidimensional arrays to functions:

All the above examples handled the one-dimensional array. What if the array being passed is multidimensional ( has two or more dimensions). For passing multidimensional arrays to a function we need to pass the name of the array similar to a one-dimensional array.

When a function argument is an array of more than one dimension, we must declare the size of the dimensions. However, the size of the first dimension is optional. 

Like for passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified.

Let’s have a look at an example:

C

#include <stdio.h>

void display(int arr[][4]){
    for(int i=0;i<2;i++){
        for(int j=0; j<4 ; j++ ){
            printf("num [%d][%d]: %d \n", i, j, arr[i][j]);
        }
    }
}
int main()
{
   int num[2][4] = { { 1,2,3,4} , { 2,3,4,5} };
   display(num);
   return 0;
}

OUTPUT

num [0][0]: 1
num [0][1]: 2
num [0][2]: 3
num [0][3]: 4
num [1][0]: 2
num [1][1]: 3
num [1][2]: 4 
num [1][3]: 5

C++

#include <iostream>

using namespace std;
void display(int arr[][4]){  
    for(int i=0;i<2;i++){
        for(int j=0; j<4 ; j++ ){
            cout<<"num ["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
        }
    }
}
int main()
{
   int num[2][4] = { { 1,2,3,4} , { 2,3,4,5} };
   display(num);
   return 0;
}

OUTPUT

num [0][0]: 1
num [0][1]: 2
num [0][2]: 3
num [0][3]: 4
num [1][0]: 2
num [1][1]: 3
num [1][2]: 4
num [1][3]: 5

Points to remember:

  • Passing arrays to functions in C/C++ are passed by reference. Even though we do not create a reference variable, the compiler passes the pointer to the array, making the original array available for the called function’s use. Thus, if the function modifies the array, it will be reflected back to the original array.
  • The equivalence between arrays and pointers to an array is valid only and only for the function arguments.
  • If an argument is a multidimensional array, its size must be specified. However, the size of the first dimension is optional. 

For example:

void check(int multiDimensional[3][4]){
    ---
    ---
}
void check(int multiDimensional[][4]){  //first dimension is optional
    ---
    ---
}

Both the above functions are acceptable, and in both of them, the receiving parameter multiDimensional is automatically converted to array pointer ( of int type).

Frequently asked questions

When we pass an array as an argument to a function, what do we pass in C++?

Only the array’s name is used when automatically we invoke a function by passing an array as an argument.
For example – display(marks); Here, the argument marks represent the memory address of the first element of array marks[5].

Can you pass an array by reference in C++?

There is usually no need to pass an array explicitly by reference because arrays are always passed by reference.

How do I change the size of a dynamic array?

Arrays are of fixed size. You cannot change the size of the array. The alternative is to declare the other array, which needs to be larger than the previous array and copies the elements to the new array.

Passing arrays to functions in C/C++ behaves differently. Why?

Passing arrays to functions in C/C++ behaves differently because no parameter can receive an entire array. The compiler converts an array declaration into an array pointer.

Why do you need to send the size of an array to a function?

Usually, the name of the array “decays” to a pointer to its first element. That means you no longer know the size of that array, as you can only pass around a pointer to an element in that array. So you have to pass its size, so the function receiving the “array” knows how long it is.

What is the difference between arrays and pointers?

An array is a collection of variables belonging to the corresponding data type. It carries the same size. In contrast, a Pointer is a single variable that stores the address of another variable.

Key Takeaways

To conclude, we’ve discussed the three ways of passing arrays to functions in C/C++. The key point is that in every way, an array is passed as the reference. The compiler automatically converts the array into the pointer array. Also, If an individual element of an array is passed to a function, it is passed according to its underlying data type.

Tadda, you made it here; kudos for your efforts.  

Don’t stop here Ninja, get yourself enrolled in a free guided path and practice the coding questions on code studio

Happy Learning Ninja!