Passing Arrays to a Function in C++ Programming


Introduction

In C++, arrays are passed to functions by reference, meaning that the function receives the address of the first element of the array rather than a copy of the entire array. This allows the function to modify the array’s contents. Understanding how arrays are passed to functions is crucial for managing memory and optimizing performance in your programs.

In this blog post, we will:

  • Explore how arrays are passed to functions in C++.
  • Look at different ways of passing arrays (by reference and by pointer).
  • Walk through practical examples to help solidify your understanding of passing arrays to functions.

1. How Arrays Are Passed to Functions in C++

In C++, arrays are always passed by reference to functions. When you pass an array to a function, the function does not receive a copy of the array but rather the memory address of the first element. This means any changes made to the array inside the function will affect the original array.

Example of Passing an Array to a Function:

#include <iostream>
using namespace std;

// Function to modify the array
void modifyArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2; // Double each element in the array
    }
}

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    modifyArray(numbers, 5); // Passing the array to the function

    // Display the modified array
    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

Output:

2 4 6 8 10

Explanation:

  • In this example, the function modifyArray() takes an array arr[] and its size as arguments.
  • The array numbers[] is passed to the function, and inside the function, each element is doubled.
  • Since arrays are passed by reference, changes made inside the function modify the original array in the main() function.

2. Passing Arrays Using Pointers

Arrays in C++ can also be passed to functions using pointers. Since the name of the array is essentially a pointer to its first element, the function can directly use pointers to manipulate the array.

Example of Passing an Array Using Pointers:

#include <iostream>
using namespace std;

// Function to modify the array using pointers
void modifyArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 3; // Triple each element in the array
    }
}

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    modifyArray(numbers, 5); // Passing the array to the function using pointers

    // Display the modified array
    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

Output:

3 6 9 12 15

Explanation:

  • The function modifyArray() accepts a pointer int *arr and a size argument.
  • Inside the function, we use pointer arithmetic to access and modify the elements of the array.
  • Passing arrays using pointers is equivalent to passing by reference, but it allows more flexibility when working with array elements at a lower level.

3. Passing Arrays with Fixed Size

If the size of the array is known at compile time, you can specify the size of the array in the function declaration. However, this is not very flexible since the array size must be fixed.

Example of Passing Arrays with Fixed Size:

#include <iostream>
using namespace std;

// Function to modify a fixed-size array
void modifyArray(int arr[5]) {
    for (int i = 0; i < 5; i++) {
        arr[i] *= 4; // Quadruple each element
    }
}

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    modifyArray(numbers); // Passing the array to the function

    // Display the modified array
    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

Output:

4 8 12 16 20

Explanation:

  • The array is passed to the function modifyArray() where the array size is fixed as 5.
  • The elements are quadrupled inside the function, and since arrays are passed by reference, the changes are reflected in the original array.

4. Using std::array (C++11 and Beyond)

If you want to pass arrays with a fixed size and have type safety and flexibility, you can use std::array (available from C++11). std::array is a container that wraps around arrays and allows for easier manipulation and size tracking.

Example of Passing std::array:

#include <iostream>
#include <array>
using namespace std;

// Function to modify a std::array
void modifyArray(std::array<int, 5>& arr) {
    for (int i = 0; i < arr.size(); i++) {
        arr[i] *= 5; // Multiply each element by 5
    }
}

int main() {
    std::array<int, 5> numbers = {1, 2, 3, 4, 5};
    modifyArray(numbers); // Passing std::array by reference

    // Display the modified array
    for (int i = 0; i < numbers.size(); i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

Output:

5 10 15 20 25

Explanation:

  • The array numbers is of type std::array<int, 5>, which holds 5 integers.
  • We pass the array by reference to the modifyArray() function, and each element is multiplied by 5.
  • The std::array class offers the benefit of size tracking and more member functions compared to regular arrays.

5. Passing Arrays with Dynamic Size (Using Pointers)

If you need to pass arrays of dynamic size, you can allocate memory dynamically using new and pass the pointer to the function.

Example of Passing Dynamically Allocated Arrays:

#include <iostream>
using namespace std;

// Function to modify a dynamically allocated array
void modifyArray(int* arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 6; // Multiply each element by 6
    }
}

int main() {
    int size = 5;
    int* numbers = new int[size]{1, 2, 3, 4, 5}; // Dynamically allocated array
    modifyArray(numbers, size); // Passing the dynamically allocated array

    // Display the modified array
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }

    delete[] numbers; // Free the dynamically allocated memory
    return 0;
}

Output:

6 12 18 24 30

Explanation:

  • We dynamically allocate an array of size 5 using new.
  • The modifyArray() function receives a pointer to the dynamically allocated array and modifies its elements.
  • After using the array, we free the allocated memory using delete[] to prevent memory leaks.

6. Best Practices for Passing Arrays to Functions

  • Pass by Reference: In most cases, it’s efficient to pass arrays by reference, allowing you to modify the original array directly.
  • Use Pointers: If you’re working with pointer-based arrays, passing arrays using pointers can give you more control and flexibility.
  • Track Array Size: Always pass the array size explicitly, as C++ does not track array size in functions (except with std::array or dynamically allocated arrays).
  • Use std::array for Fixed-Size Arrays: When possible, prefer using std::array over raw arrays for better type safety and ease of use.
  • Dynamically Allocate for Variable Size Arrays: Use new for arrays when the size is not known at compile time and deallocate memory properly using delete[].