Passing Array to Function

An array can be passed into a function either as:

  • pointer
  • sized array
  • unsized array
#include <stdio.h>

double avgFunc(int *passedArray, int passedSize)
{
	double average, total;

	for (int i = 0; i < passedSize; ++i)
	{
		total += passedArray[i];
	}

	average = total / passedSize;

	return average;
}

int main ()
{
	int myArray[7] = {98, 82, 73, 57, 65, 76, 44};
	double avgGrade;

	avgGrade = avgFunc( myArray, 7 ) ; //pass array and its size to the function

	printf( "You have an average grade of: %2.2f ", avgGrade ); //display returned average
	//note the %2.2f is simply setting the precision of the float to 2 wide 2 decimal places

	return 0;
}

The array identifier and its size are sent as arguments to the function on line 22:

avgGrade = avgFunc( myArray, 7 ) ;

 

The function receives these as a pointer to the array and its size, on line 3:

double avgFunc(int *passedArray, int passedSize)

 

The first argument in the function's interface could alternatively have been:

  • int *passedArray
  • int passedArray[7]
  • int passedArray[ ]

Leave a Reply