Passing Array as a Pointer
In this method, we pass the memory address of the first element of the array. This method also allows for dynamic array sizes.
Syntax
return_type function_name (datatype *array_name)
Example
The below example demonstrates how to pass array as a pointer to function.
C++
// C++ program to demonstratethe passing of array by // pointer. #include <iostream> using namespace std; // function to print array elements void printarray( int * a) { for ( int i = 0; i < 5; i++) *(a + i) = *(a + i) + 5; } int main() { // array creation int a[5] = { 1, 2, 3, 4, 5 }; printarray(a); // Passing array to function for ( int i = 0; i < 5; i++) cout << a[i] << " " ; return 0; } |
6 7 8 9 10
Pass Array to Functions in C++
In C++, a collection of elements stored in contiguous memory locations and having the same data type is called an array. Passing arrays to functions is done to perform various operations on array elements without messing up with the main code.
In C++, an array can be passed in a function using a pointer or reference. Understanding the different approaches to pass arrays is important for writing code according to the needs.