Passing Arrays to Functions in C++
Arrays can be passed to functions by specifying the array name without brackets. Functions can then work on the entire array.
Example: Passing an Array to a Function
#include <iostream>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
Explanation: The printArray
function takes an array and its size as arguments, allowing it to iterate and print the array's elements.
Key Takeaways
- Arrays are passed by reference (without copying).
- The function can access and modify array elements.
- Specify the array size as an additional parameter for flexibility.