Back to C++
2025-11-277 min read

Pass Arrays (C++)

Learn Pass Arrays (C++) step by step with clear examples and exercises.

Why This Matters

Understanding how to pass arrays in C++ is crucial for writing efficient programs, especially when dealing with large datasets or complex algorithms. It is vital for interview preparation, real-world programming tasks, and debugging common errors that arise during array manipulation. Properly passing arrays can help avoid unnecessary memory allocation, reduce function call overhead, and ensure the integrity of data.

Prerequisites

Before diving into passing arrays in C++, it's important to have a solid understanding of the following concepts:

  1. Basic C++ syntax, including variables, operators, and control structures (if-else, loops)
  2. Data types and their sizes
  3. Pointers and memory management
  4. Function definitions and parameters
  5. Understanding of array basics such as dimensions, indexing, and initialization
  6. Familiarity with standard library functions like std::swap, std::sort, and std::vector
  7. Comprehension of classes, objects, and the concept of object-oriented programming (OOP)
  8. Understanding of exception handling using try, catch, and throw keywords

Core Concept

Passing Arrays by Value

When an array is passed to a function by value, the entire contents of the array are copied into the function's local storage. This can lead to performance issues when dealing with large arrays or multiple function calls.

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

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, sizeof(arr) / sizeof(arr[0]));
// Modifying the array inside the function has no effect on the original array
for (int i = 0; i < 5; ++i) {
arr[i] *= 2;
}
printArray(arr, sizeof(arr) / sizeof(arr[0])); // Output: 1 2 3 4 5 (original array is not modified)
}

Passing Arrays by Reference

To avoid the performance overhead of copying arrays when passing them to functions, we can pass them by reference. This allows the function to manipulate the original array directly.

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

void modifyArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
arr[i] *= 2;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, sizeof(arr) / sizeof(arr[0])); // Output: 1 2 3 4 5
modifyArray(arr, sizeof(arr) / sizeof(arr[0]));
printArray(arr, sizeof(arr) / sizeof(arr[0])); // Output: 2 4 6 8 10 (array is modified)
}

Passing Arrays to Functions with Multiple Parameters

When passing arrays along with other parameters, ensure that the array's size is passed separately. This allows the function to handle arrays of different sizes correctly.

void printArrayAndSum(int arr[], int size, int &sum) {
sum = 0;
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
sum += arr[i];
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
printArrayAndSum(arr, sizeof(arr) / sizeof(arr[0]), sum);
std::cout << "The sum is: " << sum << "\n"; // Output: The sum is: 15
}

Using std::vector for Dynamic Array Management

Instead of manually managing array size, consider using the std::vector class from the standard library. It provides dynamic memory management and supports various operations like push_back(), pop_back(), resize(), and at().

#include <vector>

void printVector(const std::vector<int>& vec) {
for (const auto& element : vec) {
std::cout << element << " ";
}
}

int main() {
std::vector<int> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
printVector(arr); // Output: 1 2 3 4 5
}

Worked Example

Consider a problem where we need to find the second-highest number in an array. Let's write a function that takes an array and its size as input, finds the second-highest number, and returns it using a std::pair.

#include <algorithm>
#include <vector>
#include <utility>

std::pair<int, int> findSecondHighest(const std::vector<int>& arr) {
std::vector<int> sortedArr(arr);
std::sort(sortedArr.begin(), sortedArr.end());

if (sortedArr.size() < 2) {
return std::make_pair(-1, -1); // No second-highest number if the array has only one element or is empty
}

int first = sortedArr[sortedArr.size() - 2];
int second = sortedArr[sortedArr.size() - 1];
return std::make_pair(first, second);
}

int main() {
std::vector<int> arr = {10, 5, 20, 8, 11, 6};
auto result = findSecondHighest(arr);
if (result.first != -1) {
std::cout << "Second highest number: " << result.first << "\n";
} else {
std::cout << "No second-highest number found.\n";
}
}

Common Mistakes

  1. Forgetting to pass the array size as a separate argument when passing arrays by reference.
void modifyArray(int arr[], int size) { /* ... */ } // Correct
void modifyArray(int arr[]) { /* ... */ } // Incorrect (size not passed)
  1. Assuming that modifying an array passed by reference will affect the original array outside the function.
void printArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
}

void modifyArray(int arr[]) {
// This modification does not affect the original array because the size is not known within the function
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
arr[i] *= 2;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, sizeof(arr) / sizeof(arr[0])); // Output: 1 2 3 4 5
modifyArray(arr);
printArray(arr, sizeof(arr) / sizeof(arr[0])); // Output: 2 4 6 8 10 (array is modified within the function but not in main)
}
  1. Using pointers instead of references when passing arrays by reference can lead to unexpected behavior due to pointer arithmetic.
void modifyArray(int *arr, int size) { /* ... */ } // Incorrect (pointer arithmetic)
void modifyArray(int arr[], int size) { /* ... */ } // Correct (array subscripting)
  1. Not handling the case when an array has only one element or is empty in functions that expect at least two elements.
std::pair<int, int> findSecondHighest(const std::vector<int>& arr) {
// ... (rest of the function)
if (sortedArr.size() < 2) {
return std::make_pair(-1, -1); // No second-highest number if the array has only one element or is empty
}
// ... (rest of the function)
}

Practice Questions

  1. Write a function that takes an array of integers and its size, sorts the array in ascending order using bubble sort, and returns the sorted array as a std::vector.
  2. Write a function that finds the kth largest number in an array. Use a priority queue to store the k largest numbers found so far.
  3. Given two arrays of equal size, write a function that compares their elements pairwise and returns true if both arrays are identical, false otherwise.
  4. Write a function that takes an array of integers and its size, finds the median (middle value) of the array, and returns it. If the array has an odd number of elements, return the middle element; if the array has an even number of elements, return the average of the two middle elements.
  5. Write a function that takes an array of integers and its size, finds the mode (the most frequently occurring element) of the array, and returns it. If there are multiple modes, return any one of them.
  6. Write a function that takes an array of integers and its size, and checks if the array contains any duplicate elements. Return true if there are duplicates, false otherwise. Use an unordered_map to store unique elements and their counts.

FAQ

What happens when we pass an array to a function without specifying its size?

  • When an array is passed without specifying its size, the compiler assumes it's being passed by value, and the entire contents of the array are copied into the function's local storage. This can lead to performance issues when dealing with large arrays or multiple function calls.

Why should I use references instead of pointers when passing arrays to functions?

  • When passing arrays by reference, we avoid pointer arithmetic and the need for explicit memory management. Array subscripting (arr[i]) is more intuitive than pointer dereferencing (*ptr) and less prone to errors.

Can I pass a multidimensional array as a function argument?

  • Yes, you can pass a multidimensional array to a function by passing each dimension's size separately or using a single pointer that points to the first element of the array. However, be aware that this can lead to more complex code and potential memory issues.

What is the difference between passing an array by value and passing a pointer to an array?

  • Passing an array by value results in copying the entire contents of the array into the function's local storage, while passing a pointer to an array allows the function to manipulate the original array directly. When passing a pointer to an array, it is essential to pass the size of the array as well to avoid undefined behavior.

Can I return multiple values from a function in C++?

  • In C++, you cannot return multiple values directly from a function. However, you can use a struct or a class to group related data and return an instance of that type from the function. Another option is to pass additional output parameters as references to the function. Additionally, C++17 introduced std::tuple for returning multiple values from a function.
Pass Arrays (C++) | C++ | XQA Learn