Character Sequences: Arrays As Parameters
Character Sequences: Arrays As Parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a
complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In
practice this has almost the same effect and it is a much faster and more efficient operation.
In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify
in its parameters the element type of the array, an identifier and a pair of void brackets [] . For example, the
following function:
void procedure (int arg[])
accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:
int myarray [40];
it would be enough to write a call like this:
procedure (myarray);
Here you have a complete example:
// arrays as parameters
#include <iostream>
using namespace std;
void printarray (int arg[], int length) {
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n";
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}
5 10 15
2 4 6 8 10
As you can see, the first parameter (int arg[] ) accepts any array whose elements are of type int, whatever its
length. For that reason we have included a second parameter that tells the function the length of each array that
Character Sequences
As you may already know, the C++ Standard Library implements a powerful string class, which is very useful to
handle and manipulate strings of characters. However, because strings are in fact sequences of characters, we can
represent them also as plain arrays of char elements.
For example, the following array:
char jenny [20];
is an array that can store up to 20 elements of type char. It can be represented as:
Therefore, in this array, in theory, we can store sequences of characters up to 20 characters long. But we can also
store shorter sequences. For example, jenny could store at some point in a program either the sequence "Hello"
or the sequence "Merry christmas", since both are shorter than 20 characters.
Therefore, since the array of characters can store shorter sequences than its total length, a special character is
used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\0'
(backslash, zero).
Our array of 20 elements of type char, called jenny, can be represented storing the characters sequences "Hello"
and "Merry Christmas" as:
Notice how after the valid content a null character ('\0' ) has been included in order to indicate the end of the
sequence. The panels in gray color represent char elements with undetermined values.