Passing arrays as parameters to functions in C

Arrays can be passed as parameters to the functions in the following ways:

1. Passing individual elements of the array

Individual elements of an array can be passed to a function either by passing their address or the data values.

a) Passing by data values
  • The elements can be passed in the same manner as we pass the variables of other data type.
  • The only thing is that the data type of the array element should match the type of the function parameter.

Example

void main()     // Calling function
{
        int score[5] = {2,4,6,8,10};
        func (score[3]);
}

void func (int n)     // Called function
{
       printf("%d",n);
}


In the above example, one element of the array is passed to the called function.

b) Passing addresses
  • We can pass the elements by using the address operator (&) to the elements referenced index.
  • Since, we need to pass an address to the function we will use the indirection (*) operator.

Example

void main()     // Calling function
{
        int score[5] = {2,4,6,8,10};
        func (score[3]);
}
void func (int *n)     // Called function
{
        printf("%d",n);
}

2. Passing the entire array

  • While passing an entire array to a function we need to write only the name without the square brackets and the subscripts.
  • The formal argument which is corresponding is written in the same way but is declared inside the function.
  • The array dimension cannot be included in the formal declaration of the array.

Example

void main()     // Calling function
{
        int score[5] = {2,4,6,8,10};
        func (score);
}
void func (int score[5])     // Called function
{
        int i;
        for (i=0; i<5; i++)
        printf("%d",score[i]);
}