Wednesday, November 2, 2011

Passing an Entire Array to a Function in C programming language

In the previous section we saw two programs—one in which we passed individual elements of an array to a function, and another in which we passed addresses of individual elements to a function. Let us now see how to pass an entire array to a function rather than its individual elements. Consider the following example:

/* Demonstration of passing an entire array to a function */
main( )
{
      int  num[ ] = { 24, 34, 12, 44, 56, 17 } ;
      dislpay ( &num[0], 6 ) ;
}

display ( int  *j, int  n ) 
{
int  i ; 

  for ( i = 0 ; i <= n - 1 ; i++ )
 {
    printf ( "\nelement = %d", *j ) ;
    j++ ;  /* increment pointer to point to next element */
 }
}

Here, the display( ) function is used to print out the array elements. Note that the address of the zeroth element is being passed to the display( ) function. The for loop is same as the one used in the earlier program to access the array elements using pointers. Thus, just passing the address of the zeroth element of the array to a function is as good as passing the entire array to the function. It is also necessary to pass the total number of elements in the array, otherwise the display( ) function would not know when to terminate the for loop. Note that the address of the zeroth element (many a times called the base address) can also be passed
by just passing the name of the array. Thus, the following two function calls are same:

display ( &num[0], 6 ) ;
display ( num, 6 ) ;

No comments:

Post a Comment