What is the method for passing array parameters in C++?

In C++, there are several ways to pass an array as a parameter to a function:

  1. Passing pointers: You can pass the base address of an array as a pointer to a function. The function can access the elements of the array using the pointer. Example code is shown below:
void foo(int* arr, int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    foo(arr, size);
    return 0;
}
  1. Passing by reference: Arrays can be passed by reference to a function. The elements of the array can still be accessed through the array name in the function. Example code is as follows:
void foo(int (&arr)[5]) {
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    foo(arr);
    return 0;
}
  1. Template Parameters Usage: Template parameters can be used to pass arrays, allowing for compatibility with arrays of different lengths. Example code is provided below:
template<typename T, size_t size>
void foo(T (&arr)[size]) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

int main() {
    int arr1[] = {1, 2, 3, 4, 5};
    foo(arr1);

    double arr2[] = {1.1, 2.2, 3.3, 4.4, 5.5};
    foo(arr2);
    return 0;
}

Note: When using an array as a function parameter, a copy of the array is passed, and modifying elements inside the array will not affect the original array. If you want to modify the original array within the function, you can use pointers or references as parameters.

Leave a Reply 0

Your email address will not be published. Required fields are marked *