Back to C++
2026-01-218 min read

C++ Passing Arrays to Functions

Learn C++ Passing Arrays to Functions step by step with clear examples and exercises.

Why This Matters

Welcome back to another exciting lesson on C++! Today, we'll delve into an essential aspect of C++ programming: passing arrays to functions. This skill is crucial for writing efficient and reusable code, and it's something you'll encounter frequently in your coding journey. Let's get started!

Why is Passing Arrays to Functions Important?

In real-world applications, dealing with large amounts of data is common. Arrays allow us to store multiple values of the same data type efficiently. However, manipulating arrays can be complex, and that's where functions come in handy. By passing arrays as arguments to functions, we can reuse code and make our programs more modular and easier to manage.

Moreover, understanding how to pass arrays to functions is crucial for acing coding interviews and solving real-world programming problems. It's also essential for debugging your own code when you encounter issues with array manipulation.

Real-World Applications

  1. Data Processing: Passing arrays to functions allows us to process large datasets efficiently, such as sorting, searching, or filtering data.
  2. Algorithms: Many algorithms require the processing of arrays, and passing them to functions makes it easier to implement these algorithms in our programs.
  3. User Input: Functions that take arrays as arguments can handle user input more effectively, especially when dealing with multiple inputs at once.
  4. Code Reusability: By writing reusable functions, we can avoid duplicating code and make our programs more maintainable.

Prerequisites

Before diving into passing arrays to functions, it's important that you have a solid understanding of the following concepts:

  1. C++ Basics: Variables, data types, operators, control structures (if-else, loops), and functions. If you're not familiar with these topics, consider checking out our previous lessons on C++ basics.
  2. Arrays: Understanding how to declare, initialize, and access array elements is crucial for working with arrays in this lesson. You should also be familiar with pointer concepts, as they will be important when discussing passing arrays by reference.
  3. Function Overloading: While not strictly necessary, understanding function overloading can help you write more versatile functions that handle different types of arrays.

Core Concept

In C++, we can pass arrays to functions by value or by reference. Let's explore both methods and their implications.

Passing Arrays by Value

When we pass an array as a function argument by value, the entire array is copied and sent to the function. This might seem efficient for small arrays, but it can lead to performance issues when dealing with large arrays due to the overhead of copying data. Here's an example:

void printArray(int arr[]) {
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
cout << arr[i] << " ";
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr);
return 0;
}

In the above example, we've defined a function printArray that takes an array of integers as an argument. Inside the function, we iterate through the array and print its elements. In the main function, we declare an integer array arr, pass it to the printArray function, and execute it.

Passing Arrays by Reference

Passing arrays by reference is a more efficient approach when dealing with large arrays. Instead of copying the entire array, we pass a reference (a variable that refers to another variable) to the function. This way, the function can directly manipulate the original array without creating a new copy. Here's an example:

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}

In this example, we've modified the printArray function to take two arguments: the array and its size. Inside the function, we use the provided size instead of calculating it ourselves. In the main function, we pass both the array and its size to the printArray function by reference.

Passing Arrays by Pointer

Another way to pass arrays to functions is by using pointers. When we pass a pointer to an array as a function argument, the function receives a pointer to the first element of the array. Here's an example:

void printArray(int* arr, int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}

In this example, we've defined a function printArray that takes a pointer to an integer array and its size as arguments. Inside the function, we iterate through the array using pointer dereferencing (arr[i]). In the main function, we pass both the array and its size to the printArray function by pointer.

Common Mistakes

  1. Forgetting to pass the size of the array: When passing arrays by reference or pointer, it's essential to provide the size of the array as a separate argument to ensure that the function knows how many elements to process.
  2. Not handling empty or null arrays: It's important to check if an array is empty or null before processing it in your functions to avoid runtime errors.
  3. Confusing array indices with pointers: In C++, arrays and pointers are closely related. Be careful not to mix up array indices (e.g., arr[i]) with pointer dereferencing (e.g., *ptr).
  4. Not returning the modified array when passing by value: If you pass an array by value and modify it inside a function, the changes will only be visible within the function. To return the modified array to the calling function, consider using a return statement or a reference.
  5. Using sizeof incorrectly: When working with arrays, it's essential to use the correct form of sizeof. In our examples, we used sizeof(arr) / sizeof(arr[0]), which calculates the size of the array in terms of its elements.
  6. Not understanding array decay: Array decay is a concept in C++ where an array "decays" into a pointer when passed as an argument to a function. This means that the function receives a pointer to the first element of the array instead of the entire array. Be aware of this behavior and how it affects your functions.

Worked Example

Let's walk through a worked example to better understand passing arrays to functions in C++.

Problem Statement

Write a function that finds the maximum value in an integer array. The function should take the array as an argument and return the maximum value.

Solution 1 (Passing by Value)

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

int main() {
int arr[] = {5, 3, 8, 4, 7};
cout << "The maximum value in the array is: " << findMax(arr, sizeof(arr) / sizeof(arr[0])) << endl;
return 0;
}

In this example, we've defined a function findMax that takes an array and its size as arguments. Inside the function, we initialize a variable max to the first element of the array and then iterate through the rest of the array. If we find an element greater than max, we update max with the new value. Finally, we return max. In the main function, we declare an integer array arr, call the findMax function to find the maximum value, and print the result.

Solution 2 (Passing by Reference)

void findMax(int arr[], int size, int& max) {
max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
}

int main() {
int arr[] = {5, 3, 8, 4, 7};
int max = INT_MIN; // Initialize max to a small integer value
findMax(arr, sizeof(arr) / sizeof(arr[0]), max);
cout << "The maximum value in the array is: " << max << endl;
return 0;
}

In this example, we've defined a function findMax that takes an array, its size, and a reference to an integer (max) as arguments. Inside the function, we initialize max to a small integer value, set it to the first element of the array, and then iterate through the rest of the array. If we find an element greater than max, we update max with the new value. Finally, we don't return anything from the function; instead, we modify the max variable passed as a reference. In the main function, we declare an integer array arr, initialize max to a small integer value, call the findMax function to find the maximum value, and print the result.

Practice Questions

  1. Write a function that sorts an integer array using bubble sort.
  2. Modify the findMax function to find the minimum value in an integer array.
  3. Write a function that reverses an array of integers.
  4. Write a function that finds the sum of all elements in an integer array.
  5. Implement a function that swaps two elements in an array at specified indices.
  6. Write a function that finds the second-largest value in an integer array.
  7. Write a function that finds the kth largest value in an integer array.
  8. Write a function that checks if an array contains a specific value.
  9. Write a function that removes duplicate values from an array and sorts it in ascending order.
  10. Write a function that merges two sorted arrays into one sorted array.

FAQ

  1. Why can't I pass arrays directly to functions in C++?

In C++, arrays are not first-class citizens like they are in some other languages (e.g., Python). To work around this limitation, we pass array references or pointers to functions.

  1. What happens when I pass an array by value and modify it inside the function?

When you pass an array by value, a copy of the array is created and sent to the function. Any modifications made within the function will only affect the copy and not the original array.

  1. Is it possible to pass multidimensional arrays to functions in C++?

Yes! Passing multidimensional arrays to functions works similarly to passing one-dimensional arrays, but with additional dimensions represented by pointers or references.

  1. What is array decay, and how does it affect passing arrays to functions?

Array decay is a concept in C++ where an array "decays" into a pointer when passed as an argument to a function. This means that the function receives a pointer to the first element of the array instead of the entire array. Be aware of this behavior and how it affects your functions.

  1. What are some common pitfalls when working with arrays and functions in C++?

Common pitfalls include forgetting to pass the size of the array, not handling empty or null arrays, confusing array indices with pointers, using sizeof incorrectly, and not returning modified arrays when passing by value. Additionally, be mindful of array decay and its implications when working with functions.

C++ Passing Arrays to Functions | C++ | XQA Learn