Passing Array to Function


In a function when we need to pass a list of elements then we use array.


Declaring Function with array in parameter list:

There are two different ways through which a function can be declared with an array in the parameter list that are by value and by using reference.

  1. An array can be in the parameter itself. Consider the following line of code in which we have declared a function with array in the parameter list:

int addition (int array []);

  1. We can pass pointer to the function which will hold the array. Consider the following line of code in which pointer is passed in the parameter list:

int addition (int *ptr);


Returning array from function:

An array is not returned by the function but we return a pointer that is used to hold the array. Consider the following example:

CODE:

int * addition (int a [])

{

return a;

}

This will be discussed after discussing pointers.

Example:

Consider the following example in which we have defined a function that is used to sort the elements of the array:

CODE:

void sorting (int x [], int y)

{

 int i, j, temp ;

 for (i = 1; i < = y – 1; i ++)

 {

  for(j = 0; j < y – i; j ++)

  {

   if (x [j] > x [j + 1])

   {

    temp = x [j];

    x [j] = x [j + 1];

    x [j + 1] = temp;

   }

  }

 }

 for (i = 0; i < 5; i ++)

 {

  printf (“\t%d”, x [i]);

 }

}

The above function has a void data type which specifies that the function does not return any value. The name of the function is “sorting”. There are two parameters of the function that are x [] and y. The variables i, j and temp are the local variables of the function.