One Dimensional Array and Function in C

Passing 1-D array elements to a function

We can pass elements of 1-D array just like any normal variables. The following example demonstrates the same.

Expected Output:

Passing the whole Array to a Function

Just like normal variables you can pass an array variable to a function. But before you do so, make sure the formal arguments is declared as an array variable of same data type. For example:

Here we are passing an array of 10 integers to function_1(), that’s why the formal argument of function_1() is also declared as an array of 10 integers.

It is optional to specify the size of the array in the formal arguments. This means you can also declare formal argument of function_1() as follows:

While learning about formal and actual arguments, we have learned that changes made in the formal arguments do not affect the actual arguments. This is not the case with arrays. When an array is passed as an actual argument, the function gets access to the original array, so any changes made inside the function will affect the original array.

Expected Output:

How it works:

The first for loop in main() function prints the initial values of the elements of an array. In line 15, new_array() function is called with an actual argument of my_arr. The Control is transferred to function new_array(). The function multiplies each element of the array by 2 and assigns back this new value to the current index. Since new_array() is working on the original array, not on a copy of the original array, any changes made by new_array() function affect the original array. When the function finishes, control again passes back to main() function, where second for loop prints the elements of the array.

1 thought on “One Dimensional Array and Function in C

Leave a Comment