C++ Passing Arrays to Functions

Arrays can be passed to a function in C++ just like any other variable. However, when passing arrays to a function, there are a few things to keep in mind.

In C++, arrays are passed to functions as pointers. This means that when you pass an array to a function, you are actually passing a pointer to the first element of the array. The size of the array is not passed as an argument, so the function must determine the size of the array using other means.

There are two ways to pass an array to a function in C++:

  1. By passing the array as a pointer
  2. By passing the array as a reference

Example 1: Pass Array as Pointer

1#include <iostream> 2using namespace std; 3 4void printArray(int *arr, int size) 5{ 6 cout << "The elements of the array are: "; 7 for (int i = 0; i < size; i++) 8 { 9 cout << arr[i] << " "; 10 } 11 cout << endl; 12} 13 14int main() 15{ 16 int arr[] = {1, 2, 3, 4, 5}; 17 int size = sizeof(arr) / sizeof(arr[0]); 18 19 printArray(arr, size); 20 21 return 0; 22}

Output: The elements of the array are: 1 2 3 4 5

In the above example, printArray is a function that takes two arguments: a pointer to an integer arr and an integer size. The function iterates over the elements of the array and prints them. In the main function, the size of the array is calculated using sizeof and passed to the printArray function along with the array itself.

Example 2: Pass Array as Reference

1#include <iostream> 2using namespace std; 3 4void printArray(int (&arr)[5]) 5{ 6 cout << "The elements of the array are: "; 7 for (int i = 0; i < 5; i++) 8 { 9 cout << arr[i] << " "; 10 } 11 cout << endl; 12} 13 14int main() 15{ 16 int arr[] = {1, 2, 3, 4, 5}; 17 18 printArray(arr); 19 20 return 0; 21}

Output: The elements of the array are: 1 2 3 4 5

In the above example, printArray is a function that takes an array arr of 5 integers by reference. The function iterates over the elements of the array and prints them. In the main function, the array arr is passed to the printArray function without its size.