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.

Press + to interact
#include <stdio.h>
void printArray(int arr[5])
{
}
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr);
return 0;
}

We aren’t receiving any compilation warnings, so that’s good.

Looking at the header of printArray, it looks like it would only work for arrays of size 5. But let’s try to modify the declaration in line 9 and pass an array of a different size (for example, 10).

Press + to interact
#include <stdio.h>
void printArray(int arr[5])
{
}
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printArray(arr);
return 0;
}

Again, the code builds fine, without any warnings or errors.

We declared the function like void printArray(int arr[5]), and it appears it would only accept arrays of size 5. But, in the second code widget, we pass an array of size 10, and the code builds fine. The question is why.

Well, the answer is because of “array decaying.” When an array gets passed into a function, it decays to a pointer. Therefore, it loses its size information, and the compiler disregards anything we write between the square brackets of the argument declaration inside the function header.

The following declarations are equivalent:

void printArray(int arr[SIZE_HERE])
void printArray(int arr[]) //no size
void printArray(int *arr) //pointer form

No matter which forms we use, the compiler will always assume the ...