An entire array can be passed as an argument to a function. To pass an array as an argument to a function, the array name must be specified, without brackets or subscripts, as an actual argument within the function call. The corresponding formal argument is written in the same manner, though it must be declared as an array within the formal argument declarations. In the formal argument declaration, the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration.
In function prototypes an empty pair of square brackets must follow the name of each array argument, thus indicating that the argument is an array. If arguments name are not included in a function declaration, then an empty pair of square brackets must follow the array argument data type. The program segment illustrates the concept of passing array as an argument to a function.
int largest (int [], int) /* function */
void main ()
{
int x [100], i, n, max; /* variable declaration */
. . . . . . .
max = largest (x, n); /* array definition */
printf (“\nLargest = %d”, max);
}
int largest (int a [], int m) /* function definition */
{
. . . . . .
}
In the main function , largest has been called. This function called. This function call contains two actual arguments i.e., the one – dimensional, integer array and m as integer variable. There is a correspondence between the actual arguments n and the formal arguments m. The functions prototype can be written without argument name as
int largest (int [], int); /* function declaration */
we know that arguments are passed to a function by value when the arguments are ordinary variables. But pass an array to a function, the values of the array elements are not passed to the function. Rather, the array name is interpreted as the address the fast array element (i.e., the address of the memory location containing the first array element). The address is assigned to the corresponding formal argument when the function is called. The formal argument therefore becomes a pointer to the first array element. Arguments that are passed in the manner are said to be passed by reference rather than by value.
when a reference is made to an array element within the function, the value of the element’s subscript is added to the value of the pointer to indicate the address of the specified array element. Therefore, any array element can be accessed from within the function. Moreover, if an array element is altered within the function, the alteration will be recognized in the calling portion of the program.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc