Latest web development tutorials

C pass an array to a function

C array C array

If you want to pass a one-dimensional array in a function as an argument, you must be in the following three ways to declare a function in the form of parameters, the results of these three statements is the same way, because each way will tell the compiler to receive a integer pointer. Similarly, you can also pass a multidimensional array as a formal parameter.

Mode 1

Formal parameter is a pointer (you can learn in the next chapter to the knowledge of the pointer):

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

Mode 2

Formal parameter is a defined array size:

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

Mode 3

Formal parameter is an array of undefined size:

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

Examples

Now, let's look at the following function that the array as a parameter, and also passed another parameter, according to the preaching of the parameters, the average return for each element 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 follows:

#include <stdio.h>
 
/* 函数声明 */
double getAverage(int arr[], int size);

int main ()
{
   /* 带有 5 个元素的整型数组 */
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   /* 传递一个指向数组的指针作为参数 */
   avg = getAverage( balance, 5 ) ;
 
   /* 输出返回值 */
   printf( "平均值是: %f ", avg );
    
   return 0;
}

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

平均值是: 214.400000

As you can see, the function, the length of the array is irrelevant, because C does not perform bounds checking form parameters.

C array C array