C Programming Tutorial
Computer Tutorial

Passing Array Elements to a Function



Passing Array Elements to a Function

Array elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function.

# include < stdio.h >
int   main( )
{

int   i  ;
int   marks[] = { 45, 64, 95, 40, 85, 79, 93 }  ;
for ( i = 1; i < = 7; i ++  )
{

display(   &marks[i] ) ;
return ( 0 );

}

}
display( int mark )
{

for ( i = 1; i < = 7; i ++  )
{

printf(" %d ",   mark ) ;

}

}

Here, we are passing an individual array element at a time to the function display( ) and getting it printed in the function display( ). Note that since at a time only one element is being passed, this element is collected in an ordinary integer variable m, in the function display( ).

\* Demonstration of call by reference *\
# include < stdio.h >
int   main( )
{

int   i  ;
int   marks[] = { 45, 64, 95, 40, 85, 79, 93 }  ;
for ( i = 1; i < = 7; i ++  )
{

display(   &marks[i] ) ;

}
return ( 0 );

}
display( int *mark )
{

{

printf(" %d ",   * mark ) ;

}

}

Here, we are passing addresses of individual array elements to the function display( ). Hence, the variable in which this address is collected (n) is declared as a pointer variable. And since n contains the address of array element, to print out the array element we are using the ‘value at address’ operator (*).