How to Pass an array to a function in C++ ?


In C++, there are two main ways to pass an array to a function:

  • Pass by reference: In this method, we pass the array as a reference to the function. This means that the function can modify the original array. Here's an example:
void myFunction(int (&arr)[5]) {
    // function code here
}

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

In the above example, we define a function myFunction that takes an array of integers as a reference. We then call this function in main and pass our myArray array to it.

  • Pass by pointer: In this method, we pass the array as a pointer to the function. This means that the function can also modify the original array. Here's an example:
void myFunction(int *arr, int size) {
    // function code here
}

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

In the above example, we define a function myFunction that takes a pointer to an integer and an integer representing the size of the array. We then call this function in main and pass our myArray array and its size to it.

Note: When passing an array to a function, it's important to pass its size as well. This is because arrays in C++ do not carry their size information with them.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.