passare un array a una funzione

Pass an Array to a Function in C++

To pass an array to a function in C++, you can follow these steps:

Step 1: Define the Function Define the function that will take an array as an argument. You can specify the array parameter using square brackets [].

Step 2: Specify Array Size (Optional) If the size of the array is fixed, you can specify the size of the array in the function parameter to indicate the expected size of the array.

Step 3: Pass the Array to the Function When calling the function, pass the array as an argument. You can simply use the name of the array without square brackets.

Step 4: Access Array Elements in the Function Inside the function, you can access the elements of the array using the array parameter and perform operations as needed.

Here's an example of how you can pass an array to a function in C++:

#include <iostream>
using namespace std;

// Step 1: Define the Function
void printArray(int arr[], int size) {
    // Step 4: Access Array Elements in the Function
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

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

    // Step 3: Pass the Array to the Function
    printArray(myArray, 5);

    return 0;
}

In this example, the printArray function takes an array arr and its size size as arguments. The function then prints the elements of the array using a for loop. When calling the function in the main function, the myArray is passed along with its size.