Using Arrays With Functions In C++

All That You Need To Know About Arrays With Functions In C++:

In this tutorial, we will discuss how arrays can be used with functions in C++. Generally, arrays can be passed to functions as arguments in the same way as we pass the variables to functions.

But the evaluation of formal parameters is slightly different when it comes to arrays. Before actually exploring the passing of arrays to functions, we need to briefly discuss the concept of a pointer to an array.

=> Check The In-Depth C++ Training Tutorials Here.

ARRAYS WITH FUNCTION

Pointer To An Array

Consider the following array containing the first five numbers of the Fibonacci sequence.

int fibSeq[5] = {1,1,2,3,5};

Let’s declare a pointer fibPtr to point this array.

int* fibPtr;
fibPtr = fibSeq;

When we print the contents of fibPtr, the output will be the first element of the fibSeq array. This is because the name of the array without square brackets evaluates to a pointer to the first element of the array. Thus in the above example, the name “fibSeq” points to the first element of the array “fibSeq”.

Below is a pictorial representation of the same:

Pointer to an Array
As shown in the above pictorial representation, fibPtr points to the first element of the array. Thus using the pointer arithmetic, we can print all the elements of the array by just using fibPtr.

For Example, expression *(fibPtr + 1) will point to the second element of the array and so on.

Let’s put this in a program and check the output of “fibSeq” and “fibPtr”:

#include <iostream>
#include <string>
using namespace std;
int main()
{
              int fibSeq[5] = {1,1,2,3,5};
              int* fibPtr;
              fibPtr = fibSeq;
              cout<<"\nfibSeq points to :"<<*fibSeq;
              cout<<"\nfibSeq[0]: "<<*fibPtr;
              cout<<"\nfibSeq[1]: "<<*(fibPtr + 1);
              cout<<"\nfibSeq[2]: "<<*(fibPtr + 2);
             cout<<"\nfibSeq[3]: "<<*(fibPtr + 3);
             cout<<"\nfibSeq[4]: "<<*(fibPtr + 4); }
}

Output:

fibSeq points to: 1

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

In the above example, we declare a pointer variable fibPtr and then make it point to the array by assigning the name of the array to fibPtr. When we do this, we make the fibPtr point to the first element of the array. Then we print all the values of an array using fibPtr.

Passing Arrays To Function

When we are dealing with functions, we pass arrays to the function in a similar way as we pass variables to the function. But we do not pass the array variable of type [].

Instead, we pass the pointer to the array i.e. the name of the array which points to the first element of the array. Then the formal parameter that accepts this pointer is actually an array variable. As we pass the pointer, we can directly modify the array inside the function.

Consider the following program that computes the square of each element of the first five elements in the Fibonacci sequence to demonstrate the passing of an array to function.

#include <iostream>
#include <string>
using namespace std;
void fibSeqSquare(int fibSeq[])
{
              for(int i=0;i<5;i++)
               {
                               fibSeq[i] *= fibSeq[i];
                }
}
int main()
{
                int fibSeq[5] = {1,1,2,3,5};
                fibSeqSquare(fibSeq);
                for(int i=0;i<5;i++)
              {
                                cout<<fibSeq[i]<<" ";
               }
}

In the above example, we calculate the square of each element in a Fibonacci sequence. This square is calculated inside a function. Hence we pass the array name to the function “fibSeqSquare” while calling the function from the main. Inside the function, we calculate the squares of each element.

As we have passed the reference to the array by the way of a pointer, whatever modifications we make to the array inside the function, will reflect the array. Hence when we print the array in the main function, we get the squares of each element as the output.

In the above example, we have seen that the array argument (formal parameter) of the function fibSeqSquare does not specify the size of the array but just the square brackets ([]) to indicate that it’s an array. This is one way of specifying the array arguments.

Another way of specifying the array argument in the formal parameter list is by specifying the size of the array inside the square brackets. Both arguments work similarly. These are simply the two ways in which we specify the array arguments.

The following example shows an Array argument specified with size.

#include <iostream>
#include <string>
using namespace std;
void displayFibSeq(int fibSeq[5])
{
               for(int i=0;i<5;i++)
              {
                                cout<<fibSeq[i]<<" ";
               }
}
int main()
{
                int fibSeq[5] = {1,1,2,3,5};
               displayFibSeq(fibSeq);
               return 0;
}

The above example has a function to display the Fibonacci sequence. The function has a parameter as an array wherein we have also specified the size of the array.

We can also pass multi-dimensional arrays to functions in the same way as shown above.

Returning Arrays From Functions

When it comes to returning an array from a function, C++ does not allow us to return an entire array from the function. However, we can make a function to return a pointer to the array. But there is a catch to it.

Consider the following piece of code:

int* funcArray()
{
                   int arr[3] = {1,2,3};
                   return arr;
}
int main()
{
                int* aryPtr = funcArray();
                cout<<aryPtr[0];
                cout<<aryPtr[1];
                cout<<aryPtr[2];
                return 0;
}

Though the above program simply returns the pointer to the first element of an array from the function, it does not perform as expected. We cannot guarantee that the program will give us the correct output. It may or may not give the correct output.

This is because we are returning the local variable from the function and we are not sure whether it will be in scope by the time it’s returned or not.

Thus, in a nutshell, C++ does not favor returning arrays from functions.

If at all we need to return arrays from the function we need to use any of the following methods:

#1) Returning Dynamically Allocated Arrays

We can return the array pointer from the dynamically allocated array. We use the operator ‘new’ to dynamically allocate the array. As it’s a dynamic array it will be in scope unless we ‘delete’ the array. Hence, the program will run fine when we return the array.

This is shown in the following Example.

#include <iostream>
#include <string>
using namespace std;

int* funcArray()
{
             int* arr = new int[3];
             arr[0]=1;
             arr[1]=2;
             arr[2]=3;

             return arr;
}
int main()
{
             int* aryPtr = funcArray();
             cout<<aryPtr[0]<<" "<<aryPtr[1]<<" "<<aryPtr[2];
             return 0;
}

Output:

1 2 3

#2) Returning Static Arrays

As static variables/arrays have scope throughout the program, we can also return static arrays from functions. We can take an example to demonstrate this. This is the same as the previous example with the only difference being that in this example we have used a static array instead of the dynamically allocated array.

#include <iostream>
#include <string>
using namespace std;
int* funcArray()
{
              static int arr[3];
              arr[0]=1;
              arr[1]=2;
              arr[2]=3;

              return arr;
}
int main()
{
                int* aryPtr = funcArray();
                cout<<aryPtr[0]<<" "<<aryPtr[1]<<" "<<aryPtr[2];
                return 0;
}

Output:

1 2 3

Note: We can also use a structure to wrap the array inside it and then return that structure. In this way, we will naturally return an array from a function. But this is not a very feasible method of returning arrays.

Conclusion

Thus in this tutorial, we have discussed arrays with respect to functions in detail. We hope this tutorial would have helped to clear all the doubts and misconceptions about C++ arrays and functions.

=> Check Out The Perfect C++ Training Guide Here.