Passing arrays to functions:
One dimensional array :
To pass a one dimensional array to a called
function, it is sufficient to list the name of the array(without any subscript) and the size of the array as argument.
For example
int arry[10],n;
/*array declaration*/
----
----
largest(arry, n); /* function call st. - passing array as actual argument*/
The call function call largest (arry, n) , Will pass
the whole array arry to the called
function. The called function expecting this call must be approximately
defined.
The largest function header might look like
The pair of brackets informs the compiler that the
arguments array is an array of numbers. It is not necessary to specify the size
of the array here.
Main()
{
int largest (float arry[], int n);
int value[4]={12, 25, 2, 67};
printf(“%d\n”,largest(value,4));
}
int largest(int arry[],int
n)
{
int i;
int max;
max=a[0];
for(i=1;i<n;i++)
if(max<a[i])
max=a[i];
return(max);
}
Consider a problem of finding the
largest value in an array of elements.
When the function call largest( value,4) is made, the
values of all elements of array value become the corresponding elements of
array a in the called function. The largest function finds the largest value in
the array and returns the result to the main.
By passing the array name, we are
infact, passing the address of the array to the called function. The array in
the called function now refers to the
same array stored in the memory that is created from the main.
Therefore, any changes made in the array in the called function will be reflected
in the original array of the main.
Passing address of parameters to the
functions is referred to as pass by address.
No comments:
Post a Comment