Course contentsShow
← C
Lesson 474 of 1,2197. PointersFree lesson

Passing arrays to functions as pointers

Passing arrays to functions as pointers

What you'll learn: How to pass an array into a function by understanding that arrays automatically "decay" into pointers.

The Secret Identity of Arrays

When you work with an array in C, like int numbers[5], the name numbers is actually a shortcut for the memory address of the very first element. Because of this, when you pass an array to a function, you aren't sending a copy of the entire list. Instead, you are just handing the function a "map" (a pointer) to where the data starts in memory.

Think of it like sharing a document. You don't photocopy a 100-page book and mail it to your friend; you simply send them a link to the digital file. Both you and your friend are looking at the exact same data.

Syntax: Brackets vs. Asterisks

Because arrays behave like pointers when passed to functions, C allows you to use two different ways to write your function parameters. Both of these tell the compiler: "I'm expecting a memory address for a list of integers."

  1. void myFunction(int *arr) — The explicit pointer way.
  2. void myFunction(int arr[]) — The "array-style" way (which the compiler turns into a pointer anyway).

Seeing it in Action

In the example below, notice how we pass myValues to the function. We don't use & because the array name is already an address. Inside the function, we can use the pointer just like an array.

#include <stdio.h>

// 'arr' is a pointer to the first element of the array
void printFirstElement(int *arr) {
    printf("The first element is: %d\n", arr[0]);
    
    // Since we have the address, we can even change the original data
    arr[0] = 100;
}

int main() {
    int myValues[] = {10, 20, 30};

    // We pass the name 'myValues', which acts as a pointer
    printFirstElement(myValues);

    // The original array was changed!
    printf("The new first element is: %d\n", myValues[0]);

    return 0;
}

Why This Matters

This behavior makes C incredibly fast. If you had an array with a million items, copying all that data every time you called a function would slow your computer to a crawl. By passing a pointer, the computer only has to move one small memory address, no matter how large the array is. However, remember the trade-off: since the function has the actual address, any changes it makes will affect the original array!

Key takeaway

When you pass an array to a function, it "decays" into a pointer to its first element, allowing the function to access and modify the original data efficiently.