passing array to function and returning array from function C++

To pass an array to a function we need not pass the whole elements of the array one by one,instead we can just pass the first address of the array.In the function to receive the array we can either use a pointer or the usual array format.

Link :Relation between array and function

If the array format is used we may or may not mentioned the size of the array,either way it works fine.But it is better to mentioned the size else we must pass another argument as the size of the array.In the program below we will pass an array to a function and receive it using a pointer and a [] syntax format.

#include <iostream>

using namespace std ;

/*** Receiving array with pointer and [] syntax ***/
void func(float *fp , float fa[] , size_t sz )
{
/*** Accessing the array through 'fp' pointer ***/
for(int i=0 ; i < sz ; i++ )
{
 cout << fp[i] << endl ;
}

cout<< “\n\n” ;

/*** Accessing through [] syntax ***/
for(int i=0 ; i < sz ; i++ )
{
 cout << fa[i] << endl ;
}

}

int main()
{
float f[5] = { 2E4 , 3.23E1 , 67.90 , 12.789 , 666.666 } ;
func( f , f , 5 ) ;

cin.get( );
return 0 ;
} 

Output,

20000
32.3
67.9
12.789
666.666
 
20000
32.3
67.9
12.789
666.666


Returning array from the function

Passing an array to a function requires only passing the first address of the array.Well obviously we can also return an array from function by passing back only the first address of the array.A program is given below demonstrating the concept of returning an array from a function as a pointer.

#include <iostream>

using namespace std ;

/*** A function returning an array ***/
int *func( int arr[] ,size_t sz )
{
for(int i=0;i< sz ; i++)
{
 arr[i]=arr[i]*i ;
}
 return i ;
}

int main( )
{
int arr[]={ 23 ,34 , 56 , 89 };
int *ii=func( arr, 4 ) ;

/*** Accessing the array returned by function ***/
for( int i=0 ; i<3 ; ++i )
{
cout<< ii[i] << endl ; 
/** or cout<< *(ii + i) << endl ; //work fine **/
}

cin.get( ) ;
return 0 ;
} 

Output

0   34   112   267


Side note

If you use user-defined type:class or structure, instead of the built-in type,you will realize that there is no need for passing or returning array from function.Once the array is declared as a type of class or structure,it is accessible from anywhere within function.But note the function must be also declared as a member function of the type.



Leave a Reply

Your email address will not be published. Required fields are marked *