As for variables, it is possible to pass an array as an argument to a function. The syntax consists in adding empty square brackets in the arguments of the function to specify that it is an array and not a variable:
void init(int tab[], int size) {
int i=0;
for (i=0; i<size; i++) tab[i]=0;
}
However, passing arrays as parameters to functions has some differences with variables. The function does not receive a copy of the array (as for variables). It receives the address of the first cell of the array. This has two major consequences:
When an array is passed as a parameter to a function, its content can be modified by the function code.
In the example above, we can see that the function returns nothing (void init()
).
It will directly modify the content of the array passed to it as a parameter.
size
is passed to the function. size
informs the function about the number of cells in the array. The keyword const
placed before an argument tells the compiler and the user of the
of the function that this argument will not be modified by the function. For example,
the following function displays an array without modifying its content:
void display(const int tab[]);
Specifying that an array cannot be modified by a function is a good programming habit. This allows some compilers to perform additional checks at compile time.
In the following exercises, we will consider the declaration of the constant NB_GRADES
and
and the following 3 arrays:
#define NB_GRADES 6
float grades1[NB_GRADES] = {10.2, 12.5, 18.5, 9.8, 13.2, 12.1};
float grades2[NB_GRADES];
float averages[NB_GRADES];
Write a function void display(const float grades[], int size)
which displays the values of the array
passed as parameter. Test your function with the array grades1
:
grade[0] = 10.20 grade[1] = 12.50 grade[2] = 18.50 grade[3] = 9.80 grade[4] = 13.20 grade[5] = 12.10
Write a function int init(float class[], int size, float value)
that fills the array class
with the note grade
.
Initialize each cell of grades2
array to 10 thanks to the function before displaying it:
grade[0] = 10.00 grade[1] = 10.00 grade[2] = 10.00 grade[3] = 10.00 grade[4] = 10.00 grade[5] = 10.00