Skip to content
StudyFame

Passing Arrays to Functions in C

In the last module, functions got a copy of each argument. Arrays are different. When you pass an array, the function gets the address of its first element, not a copy of all the elements.

In this lesson you will pass 1D and 2D arrays to functions, see why the function can change the original array, and learn the sizeof trap that catches many students.

What You Will Learn

  • How to pass a whole array to a function.
  • Why you must pass the size separately.
  • Why changes inside the function affect the original array.
  • How const protects an array from changes.
  • How to pass a 2D array.
  • How to pass a single element.

How Passing an Array to a Function Works

Exam definition: When an array is passed to a function, only the base address (address of the first element) is passed. The parameter int a[] is really a pointer int *a. So arrays are effectively passed by reference, and the function can modify the original elements.

Memory trick: Passing an array is like sharing a Google Drive link, not sending the file. Anyone with the link edits the same file. And the link doesn't say how big the folder is, so you must tell the size separately.

Syntax for Passing Arrays

/* prototype: three ways, all mean the same */
void show(int a[], int n);
void show(int a[10], int n);   /* the 10 is ignored */
void show(int *a, int n);

/* call: just the array name, no brackets */
show(marks, 5);

/* 2D array: column count is required */
void print(int m[][3], int rows);
print(matrix, 2);

/* one element: passed by value, like a normal int */
square(marks[2]);

Example 1: Function to Print an Array and Find Its Sum

#include <stdio.h>

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

int sum_array(const int a[], int n)
{
    int i, total = 0;
    for (i = 0; i < n; i++)
        total += a[i];
    return total;
}

int main(void)
{
    int marks[] = {80, 65, 90, 72, 58};
    int n = sizeof(marks) / sizeof(marks[0]);

    printf("Marks: ");
    print_array(marks, n);
    printf("Total: %d\n", sum_array(marks, n));

    return 0;
}

Output

Marks: 80 65 90 72 58
Total: 365

Code Explanation

  1. void print_array(const int a[], int n) receives the array's address and its size. const promises the function will only read the array.
  2. n is calculated in main(), where the real array exists, and then passed in.
  3. print_array(marks, n); passes the array name only. The name of an array means the address of its first element.
  4. sum_array loops through the elements and returns one int: the total.

The sizeof trap

Inside a function, sizeof(a) gives the size of a pointer (usually 8 bytes on a 64-bit system), not the size of the array. So sizeof(a) / sizeof(a[0]) inside a function gives a wrong count. Always pass n as a separate argument.

in main()     : sizeof(marks) = 20   (5 ints x 4 bytes)
in function   : sizeof(a)     = 8    (just a pointer)

Example 2: A Function That Changes the Original Array

A teacher adds 5 grace marks to every student. The function changes the array in main() directly.

#include <stdio.h>

void add_grace(int a[], int n, int grace)
{
    int i;
    for (i = 0; i < n; i++)
    {
        a[i] = a[i] + grace;
        if (a[i] > 100)
            a[i] = 100;
    }
}

void print_matrix(int m[][3], int rows)
{
    int i, j;
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < 3; j++)
            printf("%3d", m[i][j]);
        printf("\n");
    }
}

int main(void)
{
    int marks[] = {80, 97, 35, 60};
    int seats[2][3] = { {1, 2, 3}, {4, 5, 6} };
    int i;

    add_grace(marks, 4, 5);

    printf("After grace marks:");
    for (i = 0; i < 4; i++)
        printf(" %d", marks[i]);
    printf("\n");

    printf("Seat matrix:\n");
    print_matrix(seats, 2);

    return 0;
}

Output

After grace marks: 85 100 40 65
Seat matrix:
  1  2  3
  4  5  6
  • add_grace has no return value, yet marks in main() changed. The function worked on the same memory.
  • print_matrix(int m[][3], int rows): the column count 3 must be written, so the function can find where each row begins.

Can a Function Return an Array?

  • A function cannot return a whole array in C. int[] f() is not allowed.
  • Usual fix: let the caller create the array and pass it in; the function fills it (like Example 2).
  • Other options: return a pointer to a static array, return a pointer from malloc, or wrap the array inside a struct.
  • Never return the address of a local array: it is destroyed when the function ends.

Important Points to Remember

  • Passing an array passes its base address, not a copy.
  • int a[] as a parameter is the same as int *a.
  • Changes in the function affect the original array.
  • Always pass the size; sizeof inside the function gives the pointer size.
  • Use const for arrays the function should only read.
  • For 2D arrays, the column size is required in the parameter.
  • A single element like a[2] is passed by value.

Common Mistakes Beginners Make

MistakeWhat happensFix
Calling show(marks[], 5)Compile errorshow(marks, 5)
Using sizeof(a) inside the functionWrong element countPass n from the caller
void f(int m[][], int r)Compile errorvoid f(int m[][3], int r)
Returning a local arrayDangling pointer, garbageFill an array passed by the caller
Expecting the original to stay unchangedData changed by the functionUse const or copy first

Passing Arrays to Functions Practice Questions

  1. What is actually passed when you pass an array to a function?
  2. Why must the size be passed as a separate argument?
  3. Is void f(int a[]) different from void f(int *a)?
  4. Write the prototype of a function that takes a 2D int array with 4 columns.
  5. Can a C function return an array? What do we do instead?
Show answers
  1. The base address of the array (address of its first element).
  2. The function receives only a pointer, which doesn't carry the length; sizeof there gives the pointer's size.
  3. No, as parameters they are exactly the same.
  4. void f(int m[][4], int rows);
  5. No. The caller passes an array and the function fills it (or returns a pointer to static/malloc memory, or a struct).

Coding Exercise

Write int count_above(const int a[], int n, int limit) that returns how many elements are greater than limit, and void double_all(int a[], int n) that doubles every element. Test with {3, 8, 1, 9, 6} and limit 5.

Show solution
#include <stdio.h>

int count_above(const int a[], int n, int limit)
{
    int i, count = 0;
    for (i = 0; i < n; i++)
        if (a[i] > limit)
            count++;
    return count;
}

void double_all(int a[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        a[i] *= 2;
}

int main(void)
{
    int a[] = {3, 8, 1, 9, 6};
    int i;

    printf("Above 5: %d\n", count_above(a, 5, 5));
    double_all(a, 5);
    printf("Doubled:");
    for (i = 0; i < 5; i++)
        printf(" %d", a[i]);
    printf("\n");
    return 0;
}
Above 5: 3
Doubled: 6 16 2 18 12

Quick Quiz: Passing Arrays to Functions (MCQ)

  1. When an array is passed to a function, C passes:

    A) A copy of all elements   B) The base address   C) The last element   D) The size

  2. Correct call for void show(int a[], int n); with int x[4];

    A) show(x[], 4);   B) show(&x[4], 4);   C) show(x, 4);   D) show(*x, 4);

  3. Inside void f(int a[]) on a 64-bit system, sizeof(a) is usually:

    A) Array size in bytes   B) 8   C) 4   D) Number of elements

  4. Which 2D parameter is valid?

    A) int m[][]   B) int m[3][]   C) int m[][3]   D) int m[,3]

  5. A single element a[1] passed to void g(int x) is passed:

    A) By value   B) By reference   C) As a pointer   D) As an array

Show answers
  1. B: the base address.
  2. C: show(x, 4);
  3. B: 8 (size of a pointer).
  4. C: int m[][3].
  5. A: by value.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

What is passedBase address of the array
int a[] parameterSame as int *a
Original arrayCan be changed by the function
SizePass separately
sizeof inside functionPointer size (4 or 8)
2D parameterColumn size required: m[][3]
Return an array?Not allowed directly

Frequently asked questions

Are arrays passed by value or by reference in C?
The address is passed (by value), so in effect the array is passed by reference and can be changed.
Why can't a function find the array length with sizeof?
The array decays to a pointer, so sizeof gives the pointer's size.
How do you stop a function from changing an array?
Declare the parameter as const int a[].

Remember

  • Array to function = shared link, not a copy.
  • Name only in the call, size always with it.

Next Topic

Next lesson: Insert and Delete in an Array. You will insert a new element at any position and delete an element by shifting.