Passing Arrays to Functions

Find out how arrays are passed to functions.

Introduction

Recall that we previously explored pass by value and pass by reference for variables. We discovered that the default way of passing variables as arguments is by value, and to pass by reference, we need to use a pointer.

Our current goal is to extend these notions for arrays and figure out how arrays are passed as arguments to a function.

We’ll start by writing a function to print an array. We must iterate over the array and print every element.

In this lesson, we’ll use the following array:

int arr[5];

Function header

Our function is called printArray and looks like the following code snippet:

void printArray(...)
{
}

Notice that in the header, where the arguments should be, we used ... as a placeholder. What should we write there?

Well, since our array is int arr[5], maybe we can add the same declaration in the header.

void printArray(int arr[5])
{
}

Let’s write this in code, compile, and see if the code builds fine.

Get hands-on with 1200+ tech skills courses.