C Language

How to pass an array to a function

In C Language by Baqir AliLeave a Comment

In a function definition, a parameter that is declared an array is actually a pointer. When an array is passed, its base-address is passed call-by-reference. The array elements themselves are not passed.

An entire array can be passed to a function as an argument.

  • To achieve this the parameter in the function header must be declared as an array. The array name is written followed by an empty pair of square brackets. The size of the array is not specified.

For example in the function header:

int sum(int a[ ], int n)

a is declared to be an array of type integer. So the general form of an array declaration in a function header is:

a_type a_name[ ]

where a_type is the data type of the array and a_name is the parameter name.

In a function prototype, an array argument is specified by following the data type of the argument by an empty pair of square brackets.

int sum(int [ ], int);

Since, as we have seen, an array name is essentially a pointer, it is clear that when an array is passed to a function it is passed by reference, and not by value. Hence, if any of the array elements are altered within the function then these alterations are recognized in the calling portion of the program.

Leave a Comment