Array as function argument
è The array can be passed
to function as arguments as like individual variables such as int, float, char
etc.
Pass One dimensional array
è The array can be passed to function by writing only array name in function call without
specifying its subscript, and the size of the array as arguments.
Ex, int
x[5]={1,2,3,4,5};
display(x,5); // function call
Here, x is the array
and 5 is the size of array both are of integer type.
The definition of
display() is as follow:
void display(int
x[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf(“\n %d”,x[i]);
}
}
è Here, the array
variable x is received with the empty subscript and the size 5 is received in
variable n.
è By passing the array
name, the address of the array is passed to called function. Any change in the
array in the called function will be reflected in the original array. Passing
addresses of parameters to the function is referred to as pass by address.
Consider following
rules to pass an array to a function.
1.
The function must be called by passing only the name of
the array.
2.
In the function definition, the formal parameter must be
an array type.The size of the array does not need to be specified.
3.
The function prototype must show that the argument is an
array.
Pass two dimensional array
è Like simple arrays , it
possible to pass two dimensional and multi dimensional array.
Consider following
rules:
1.
The function must be called by passing only the name of
the array.
2.
In the function definition, need to indicate that the
array has two – dimensions by including two sets of brackets.
3.
The size of second dimension must be specified.
4.
The prototype declaration must should be similar to the
function header.
Ex,
void main()
{
int mat[3][2]={{1,2},{3,4},{5,6}};
disp(m,3,2);
}
void disp(int mat[][2],int r,int c)
{
int i;
printf(“\n output \n” );
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,mat[i][j]);
}
printf(“\n”);
}
}
Posted By ; Ruchita Pandya
No comments:
Post a Comment