Passing arrays to functions in C programming

In this tutorial, we will learn about passing arrays to functions in C programming.

Like other values of variables, arrays can be passed to a function. Let us see how to pass an entire array to a function. Both one-dimensional arrays and multidimensional arrays can be passed as function arguments.

Passing one-dimensional array to the function

While passing one-dimensional array to the function name of the array is passed as actual arguments and array variable with subscript is passed as formal arguments.

Ways of passing arrays as formal arguments.

1: Passing formal parameter as pointer

void func_name( int *name )
{
.......
}

2: Passing formal parameters as sized array

void func_name( int name[10] )
{
.......
}

3: Passing formal parameters as unsized array

void func_name( int name[] )
{
.......
}

Example: C program to pass an array to the function that contains marks obtained by the student. Then display the total marks obtained by the student

Explanation:
Here, the total_marks( ) function is used to calculate total marks. The for loop is used to access the array elements.

Passing Multidimensional array to the function

Like simple arrays, multidimensional arrays can be passed to the function. Two-dimensional array is indicated by two sets of brackets with array variable. The size of second dimension must be specified.

Explanation
In the above program, we can see the difference between passing an array by reference and element by value.

The program first prints the value of array and it is passed to changeArray() function, where elements are multiplied by 2. The modified result is printed.

In the second part, the program first prints the third element of modified array. After this third element of an array is passed to changeElement() function by value, where it is multiplied by 2 and value is printed.

Finally, in the main function the value of third element of an array is printed again but the value remains same.

Note: We can use const (constant) type qualifier to prevent modification of array elements in a function.