Arrays in Functions

In this tutorial from our C++ Arrays section, we will learn how to work with arrays and functions, learning how to pass an array as an argument, how to return and receive an array, how to copy, compare and change arrays using functions.

Arrays as arguments to Functions

What basically differentiates an integer variable from an array of integers? Let's see the statements:
  • int num;
  • int num[2112];

Well, it's the pair of square brackets, with a number inside. Do you agree?
When we pass an integer to a function, its prototype is:
  • show(int num); or show(int);

So, as you might suspect, to pass an array as an argument, you can do, in the prototype:
  • show(int num[]); or show(int []);

You see, you only pass with the pair of brackets, okay? No number inside.
In the function code, the header is with: show (int num[]);

Let's give a code example of an array that we declared in main(), of integers, we pass to the show() function and it displays these elements.
Look at how we invoke the function: show (num);

The name of the array is 'num', okay? Do not: show(num[]) to invoke the function.
#include <iostream>
using namespace std;

void show(int []);

int main()
{
    int num[]={10, 20, 30};

    show(num);

    return 0;
}

void show(int num[])
{
    int count;

    for(count=0 ; count<3 ; count++)
        cout<<"Elements "<<count+1<<": "<<num[count]<<endl;
}
Got it? However, there is a problem ... the function 'already knew' beforehand that the array had 3 elements. But, well, the functions don't have a crystal ball. Therefore, it is common and usual, to pass along with the array, its size too, for the functions:
#include <iostream>
using namespace std;

void show(int [], int);

int main()
{
    int num[]={10, 20, 30, 40, 50};
    int size=5;
    show(num, size);

    return 0;
}

void show(int num[], int size)
{
    int count;

    for(count=0 ; count<size ; count++)
        cout<<"Elements "<<count+1<<": "<<num[count]<<endl;
}

When we study the vector class, in STL, we will see more dynamic and powerful types of arrays, and we will not have to worry about informing the size of the array, as it will be information specific to the structure we are going to use.

Return Array: Pass by reference

Let's create an array called num[], insert some numbers.
Next, let's move on to the doub() function, which will double each element of the array, and print it doubled.

Then, we print, now in main(), again the array num:
#include <iostream>
using namespace std;

void doub(int [], int);

int main()
{
    int num[]={10, 20, 30, 40, 50};
    int size=5, count;

    doub(num, size);

    for(count=0 ; count<size ; count++)
        cout<<num[count]<<"  ";

    return 0;
}

void doub(int num[], int size)
{
    int count;

    for(count=0 ; count<size ; count++)
        num[count] *= 2;

    for(count=0 ; count<size ; count++)
        cout<<num[count]<<"  ";

    cout<<endl;
}
The result is:
20  40  60  80  100
20  40  60  80  100

Now, look at that! You passed an array to the function. Inside it, it doubled.
When you returned from the function, to main(), and you printed the array again, it was doubled.
In other words: the function changed the array.

Although you only passed the name of the array, it changed the original array. That is: when we pass an array to a function, this pass is by reference. When we pass the array name to the function, C++ passes the actual address of the array. Thus, the function changes that memory position, directly, and not a copy of the value (as it happens when passing by value).

This is for efficiency reasons, since it would take a long time to make a copy of the arrays passed to the functions (on a day-to-day basis, we work with very large arrays).

OK? C++ passes the array by reference, don't forget!

How to copy Arrays

Often, we want to do some things with arrays, but without changing them.
For example, suppose we have 'num' array of integers, and we want another array where each element is triple the value of each element of the 'num' array.

What we can do is first create a copy of 'num', let's call it 'copy', and bang, we send 'copy' to a function that triples the elements. As the passage is by reference, it will change the values of the 'copy' and will not even know about the existence of 'num', which is unchanged.

To make a 'copyArray' function that makes a copy of an array, we need to pass both arrays as an argument to the function, as well as their size, which must be necessarily the same. Then, just copy element by element, with a loop.

See how our code looks:
#include <iostream>
using namespace std;

void copyArray(int [], int [], int);
void triple(int [], int);

int main()
{
    int num[]={10, 20, 30, 40, 50}, copy[5];
    int size=5, count;

    copyArray(num, copy, size);
    triple(copy, size);

    cout<<"Original Array: "<<endl;
    for(count=0 ; count<size ; count++)
        cout<<num[count]<<"  ";

    cout<<"\nTriplicate Array: "<<endl;
    for(count=0 ; count<size ; count++)
        cout<<copy[count]<<"  ";

    return 0;
}

void copyArray(int num[], int copy[], int size)
{
    int count;

    for(count=0 ; count<size ; count++)
        copy[count] = num[count];
}

void triple(int copy[], int size)
{
    int count;

    for(count=0 ; count<size ; count++)
        copy[count] *= 3;

}
Result:
Original Array:
10 20 30 40 50

Tripled Array:
30 60 90 120 150

If you really want to preserve the original 'num' array and really want to make sure it doesn't change, you can declare it and use it as const:

  • In the header: void copyArray(const int [], int [], int);
  • In the function declaration: void copyArray(const int num [], int copy [], int size) {...}
  • In array declaration: const int num [] = {10, 20, 30, 40, 50};

No comments:

Post a Comment