How to pass arrays to a function in C Programming?

In this article, you'll learn to arrays to a function in C programming. You'll learn to pass both one-dimensional and multi-dimensional arrays to a function.

You can pass a single array element of an array or an entire array to a function.


Passing One-dimensional Array to a Function

Passing a single element of an array to a function is similar to passing variable to a function.


Example 1: Passing single element of an array to function

#include <stdio.h>
void display(int age)
{
    printf("%d", age);
}

int main()
{
    int ageArray[] = {2, 3, 4};
    display(ageArray[2]); //Passing array element ageArray[2]
    return 0;
}

Output

4

Example 2: Passing an entire array to a function

// Program to calculate average by passing an array to a function

#include <stdio.h>
float average(float age[]);

int main()
{
	float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
	avg = average(age); // Only name of an array is passed as an argument
	printf("Average age = %.2f", avg);
	return 0;
}

float average(float age[])
{
	int i;
	float avg, sum = 0.0;
	for (i = 0; i < 6; ++i) {
		sum += age[i];
	}
	avg = (sum / 6);
	return avg;
}

Output

Average age = 27.08

To pass an entire array to a function, only the name of the array is passed as an argument. However, notice the use of [] after argument name in float average(float age[]). This informs the compiler that you are passing a one-dimensional array to the function.


Passing Multi-dimensional Arrays to Function

To pass multidimensional arrays to a function, only the name of the array is passed (similar to one dimensional array).


Example 3: Passing two-dimensional array to a function

#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
    int num[2][2], i, j;
    printf("Enter 4 numbers:\n");
    for (i = 0; i < 2; ++i)
        for (j = 0; j < 2; ++j)
            scanf("%d", &num[i][j]);

    // passing multi-dimensional array to a function
    displayNumbers(num);
    return 0;
}

void displayNumbers(int num[2][2])
{
    int i, j;
    printf("Displaying:\n");
    for (i = 0; i < 2; ++i)
        for (j = 0; j < 2; ++j)
            printf("%d\n", num[i][j]);
}

Output

Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

You can use void displayNumbers(int num[][2]) instead of void displayNumbers(int num[2][2]) in the above program.