C++ Passing Array to Function

In C++, arrays can be passed to functions to perform operations like printing, summing, or modifying elements. When an array is passed to a function, only its base address is passed.

1. Passing One-Dimensional Array

To pass a one-dimensional array, specify the array name and size (optional in parameter).

C++
Example: Passing 1D array to function
#include <iostream>
using namespace std;

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

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    printArray(numbers, 5);
    return 0;
}

2. Modifying Array Inside Function

Since arrays are passed by address, changes made inside the function affect the original array.

C++
Example: Modifying array elements
#include <iostream>
using namespace std;

void incrementArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] += 1;
    }
}

int main() {
    int numbers[3] = {1, 2, 3};
    incrementArray(numbers, 3);

    for (int i = 0; i < 3; i++) {
        cout << numbers[i] << " ";
    }

    return 0;
}

3. Passing Multi-Dimensional Array

When passing a multi-dimensional array, all dimensions except the first must be specified.

C++
Example: Passing 2D array
#include <iostream>
using namespace std;

void printMatrix(int arr[][2], int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 2; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int matrix[2][2] = {{1, 2}, {3, 4}};
    printMatrix(matrix, 2);
    return 0;
}

4. Key Points

1. Arrays are passed by address (base pointer). 2. Changes inside the function modify the original array. 3. Always pass array size to avoid out-of-bounds access. 4. For multi-dimensional arrays, specify column size in parameters.

Conclusion

Passing arrays to functions in C++ allows modular and reusable code. Understanding how arrays decay to pointers ensures correct implementation and prevents memory errors.