Wednesday, November 2, 2011

Passing Array Elements to a Function in C programming language

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. These two calls are illustrated below:

/* Demonstration of call by value */
main( )
{
      int  i ;
      int  marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;

      for ( i = 0 ; i <= 6 ; i++ )
            display ( marks[i] ) ;


display ( int  m )
{
      printf ( "%d ", m ) ;
}

And here’s the output... 

55 65 75 56 78 78 90

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( ). And now the call by reference.
/* Demonstration of call by reference */
main( )
{
      int  i ;
      int  marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;

      for ( i = 0 ; i <= 6 ; i++ )
            disp ( &marks[i] ) ;
}

disp ( int  *n )
{
      printf ( "%d ", *n ) ;
}

And here’s the output...
55 65 75 56 78 78 90

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 (*). Read the following program carefully. The purpose of the function disp( ) is just to display the array elements on the screen. The
program is only partly complete. You are required to write the function show( ) on your own. Try your hand at it.

main( )
{
      int  i ;
      int  marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;

      for ( i = 0 ; i <= 6 ; i++ )
            disp ( &marks[i] )
}

disp ( int  *n )
{
      show ( &n ) ;
}

No comments:

Post a Comment