Easy Tutorial
❮ C Examples Calculator Switch Case C Exercise Example40 ❯

Passing Arrays to Functions in C

C Arrays

If you want to pass a one-dimensional array as a parameter in a function, you must declare the function formal parameter in one of the following three ways. The result of these declarations is identical because each way tells the compiler that an integer pointer will be received. Similarly, you can also pass a multi-dimensional array as a formal parameter.

Method 1

The formal parameter is a pointer (you will learn about pointers in the next chapter):

void myFunction(int *param)
{
.
.
.
}

Method 2

The formal parameter is an array of a defined size:

void myFunction(int param[10])
{
.
.
.
}

Method 3

The formal parameter is an array of an undefined size:

void myFunction(int param[])
{
.
.
.
}

Example

Now, let's look at the following function, which takes an array as a parameter along with another parameter, and returns the average of the elements in the array:

double getAverage(int arr[], int size)
{
  int    i;
  double avg;
  double sum;

  for (i = 0; i < size; ++i)
  {
    sum += arr[i];
  }

  avg = sum / size;

  return avg;
}

Now, let's call the above function as shown below:

Example

#include <stdio.h>

/* Function declaration */
double getAverage(int arr[], int size);

int main ()
{
   /* An integer array with 5 elements */
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   /* Pass a pointer to the array as a parameter */
   avg = getAverage( balance, 5 ) ;

   /* Output the returned value */
   printf( "Average value is: %f ", avg );

   return 0;
}

double getAverage(int arr[], int size)
{
  int    i;
  double avg;
  double sum=0;

  for (i = 0; i < size; ++i)
  {
    sum += arr[i];
  }

  avg = sum / size;

  return avg;
}

When the above code is compiled and executed, it produces the following result:

Average value is: 214.400000

You can see that the length of the array is irrelevant to the function, as C does not perform boundary checking on formal parameters.

C Arrays

❮ C Examples Calculator Switch Case C Exercise Example40 ❯