passing array to function c++ pointer

When passing an array to a function in C++, you can use a pointer to access and manipulate the array elements within the function. Here are the steps involved:

  1. Declare the function: Begin by declaring the function that will accept the array as a parameter. The function declaration should include the array parameter, which is declared as a pointer.

  2. Pass the array: When calling the function, pass the array as an argument. Since arrays decay into pointers when passed to functions, you don't need to explicitly pass the size of the array.

  3. Access the array elements: Inside the function, you can access the elements of the array using the pointer notation. The pointer acts as a reference to the original array, allowing you to modify its elements.

  4. Perform operations: You can perform various operations on the array elements within the function. This can include reading values, modifying values, or performing calculations.

  5. Return from the function: If necessary, you can return a value from the function. However, keep in mind that modifications made to the array elements within the function will persist after the function returns.

Here is an example that demonstrates passing an array to a function in C++ using a pointer:

#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 arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    printArray(arr, size);

    return 0;
}

In this example, the printArray function accepts an array arr and its size size as parameters. Inside the function, the elements of the array are accessed using the pointer arr and printed to the console.

When calling the printArray function in the main function, the array arr and its size are passed as arguments. The function then prints the elements of the array.

The output of this code will be:

1 2 3 4 5

This demonstrates how you can pass an array to a function in C++ using a pointer and perform operations on the array elements within the function.