C++ Passing Arrays to Functions

ww‮figi.w‬tidea.com

In C++, you can pass arrays to functions as arguments. There are two common ways to do this: passing the array by reference or passing the array as a pointer.

Passing the array by reference means that the function receives a reference to the original array, not a copy of it. This allows the function to modify the array directly. Here's an example:

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

int main() {
    int myArray[5] = {1, 2, 3, 4, 5};
    modifyArray(myArray);
    // myArray now contains {2, 4, 6, 8, 10}
    return 0;
}

In this example, modifyArray takes an array of five int elements by reference. It then doubles each element of the array in place.

Passing the array as a pointer means that the function receives a pointer to the first element of the array. This allows the function to access the elements of the array, but it cannot modify the original array itself. Here's an example:

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

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

In this example, printArray takes a pointer to the first element of an array of int elements and the size of the array. It then loops through the array and prints each element to the console.

When you pass an array to a function as a pointer, you must also pass the size of the array as a separate argument, because the function does not know the size of the array.