Lesson 9.5. Arrays and functions

Passing arrays as arguments

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:

Keyword const

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.

Exercises

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];

Exercise 1

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

Exercise 2

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

Quiz

In C, an array passed as an argument to a function ...

Check Bravo! If arrays were copied on every function call, large arrays would cause a performance issue. Try again...

The tab array passed as argument ...

void fct(int tab[]);
Check Bravo! Actually, it is the memory address of the array (the pointer) that is passed to the function. With the address, it is possible to write to and read in the arrays. Try again...

The tab array passed as argument ...

void fct(const int tab[]);
Check Bravo! The const keyword specifies that the array should not be modified by the function. Try again...

How can a function know the size of an array?

Check Bravo! There are several solution to get the size of an array in a function. Try again...

The keyword const ...

Check Bravo! The const keyword gives additional information to the user of a function. Try again...

See also


Last update : 11/24/2022