Passing as a Sized Array
In this method, we pass the array in the same way we declare it with the array type, name, and size. As we can see, we still have to pass the size of the array as another parameter because at the end, the array will be treated as a pointer in the function.
Syntax
return_type function_name (datatype array_name [size], int size)
Example
The below example demonstrates the passing of array as sized array.
C++
// C++ program to demonstrate the passing of array as sized // array. #include <iostream> using namespace std; // function to update array elements void printarray( int a[10]) { for ( int i = 0; i < 5; i++) a[i] = a[i] + 5; } int main() { // array declaration int a[5] = { 1, 2, 3, 4, 5 }; printarray(a); // Passing array to function // printing array elements for ( int i = 0; i < 5; i++) cout << a[i] << " " ; return 0; } |
Output
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.
Contact Us