C - Passing arrays to functions

Overview

When you pass an array to a function, it decays to a pointer to its first element. Pass the length explicitly.

Learning Objectives

  • Write function signatures that accept arrays via pointers.
  • Handle array bounds correctly inside functions.

Prerequisites

Syntax

void func(int arr[], int n);
void func2(int *arr, int n);   // equivalent

Example

#include <stdio.h>

void printArray(const int arr[], int n) {
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
}

int main(void) {
    int nums[3] = {1, 2, 3};
    printArray(nums, 3);
}

Real-world patterns

#include <stdio.h>

int sum(const int *arr, int n) {
  int total = 0;
  for (int i = 0; i < n; i++) total += arr[i];
  return total;
}

int findMax(const int *arr, int n) {
  int max = arr[0];
  for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i];
  return max;
}

Common Pitfalls

  • Not passing the correct length, causing out-of-bounds access.
  • Confusing array size with sizeof(arr) inside the function (it’s the size of a pointer).

Checks for Understanding

  1. What is the type of the parameter arr in void f(int arr[])?
Show answer

It is adjusted to int*.

Expected Output

For printArray(nums, 3):

1 2 3 

Exercises

  1. Write int average(const int *arr, int n) that returns the integer average of the array.
  2. Write void reverse(int *arr, int n) that reverses the array in place.