Arrays as Parameters

Arrays as Parameters

At some moment we have a tendency to may have to pass associate degree array to a function as a parameter. In C++ it’s impracticable to pass a complete block of memory by worth as a parameter to a function, however we have a tendency to be allowed to pass its address. In practice this has nearly an equivalent result and it’s a far quicker and a lot of economical operation.

In order to just accept arrays as parameters the sole issue that we’ve got to try and do once declaring the function is to specify in its parameters the component variety of the array, associate degree symbol and a combine of void brackets []. as an example, the following function:

void passingarray (int arg[])

accepts a parameter of type “array of int” called arg. In order to pass to this function an array declared as:

int arraypram [40];

it would be enough to write a call like this:

passingarray (arraypram);

Here you have a complete example:

// arrays as parameters

#include <iostream>

using namespace std;

void showarray (int arg[], int length) {

for (int n=0; n<length; n++)

cout << arg[n] << ” “;

cout << “\n”;


int main ()


int array1 [] = {5, 10, 15};

int array2[] = {2, 4, 6, 8, 10};

showarray (array1,3);

showarray (array2,5);

return 0;



5 10 15

2 4 6 8 10

As you’ll be able to see, the primary parameter (int arg[]) accepts any array whose components square measure of type int, no matter its length. For that reason we’ve enclosed a second parameter that tells the function  the length of every array that we pass to that as its 1st parameter. This permits the for loop that prints out the array to understand the range to restate in the passed array while not going out of range.

In a function declaration it’s additionally potential to incorporate multi-dimensional arrays. The format for a tridimensional array parameter is:


for example, a function with a multi-dimensional array as argument may be:

void procedure (int myarray[][3][4])

Notice that the primary brackets [] square measure left blank whereas the subsequent ones aren’t. this can be therefore as a result of the compiler must be ready to confirm at intervals the function is that the depth of every further dimension.

Arrays, each simple or multi-dimensional, passed as function parameters square measure a quite common supply of errors for novice programmers. I would like to recommend the reading of the chapter regarding Pointers for a far better understanding on however arrays operate.

PDF tutorial Arrays as parameters