Course contentsShow
← Computer Science
Lesson 241 of 2,8726. Arrays and Basic CollectionsFree lesson

Arrays as Function Parameters

Passing arrays to functions and understanding pass-by-reference behavior in different languages.

Arrays as Function Parameters

You'll learn how to pass arrays into functions and why they behave differently from simple variables like integers.

The Core Idea

When you pass an array to a function, you're not making a copy of the entire array — instead, you're giving the function a reference to the original array's location in memory. This is fundamentally different from passing an integer or character, where the function gets its own copy to work with.

Think of it like giving directions to your house versus giving someone a copy of your house. With directions (a reference), anyone who follows them will arrive at the same house and can rearrange your furniture. With a copy, they'd get their own house and changes wouldn't affect yours.

Pass-by-Reference Behavior

def modify_array(arr):
    arr[0] = 999  # Changes the original!

my_numbers = [1, 2, 3, 4, 5]
modify_array(my_numbers)
# my_numbers is now [999, 2, 3, 4, 5]
void modify_array(int arr[], int length) {
    arr[0] = 999;  // Changes the original!
}

int my_numbers[] = {1, 2, 3, 4, 5};
modify_array(my_numbers, 5);
// my_numbers is now {999, 2, 3, 4, 5}

The function receives access to the same array in memory, not a separate copy. Any modifications inside the function affect the original array.

Why This Matters

Copying entire arrays would be slow and wasteful for large datasets. Passing by reference is efficient, but it means you must be careful — functions can inadvertently modify data you didn't intend to change.

Key Takeaway: Arrays passed to functions typically use pass-by-reference semantics, meaning the function can modify the original array's contents, unlike simple variables that are copied.