Array to function in C

We can create functions that receive an array as an argument. To pass an array into a function, we need to write the name of the array in the function call. We have to pass the size of an array as a parameter. Size may or may not be required.

Exclusion of size can be done in ‘\0’ terminated character arrays, and size can be determined by checking the end of the string character. You can pass both one dimensional and multi-dimensional arrays into the function.

A single array element or an entire array itself can be passed into the function. This passing of an array can be done for both one dimensional as well as a multi-dimensional array.

Syntax:

Passing one dimensional array:

  • Passing individual array elements to a function is almost identical to passing variables to a function.

Eg:

Output:

  • Passing an entire array to a function using pointer

Eg:

            Output:

To pass an array to a function, the name of the specific array will be passed as an argument, such as, in the above example, we pass result = totalHeight(height);

Function definition has [], in it. It informs the compiler that you are passing one dimensional array to a function.

In the above code, we can see the code snippet:

  • Passing an array using a pointer

Passing multi-dimensional array:

The multi-dimensional array can be passed to a function in the same way as we pass a one dimensional array. There are two ways in which we can pass an array into a function.

  • Passing an array directly to a function:

The simplest way to pass a multi-dimensional array is to pass it as we would for any other variables.

E.g.:

  • Passing an array to a function using pointer:

Eg:

There are three ways to pass an array to a function in the C programming language:

  • Using blank subscript notation []
  • Defining size in subscript notation []
  • Using pointer

Advantages:

  • The array is passed as a pointer; hence the memory of the array will not be copied. The function uses the memory of the same array passed to it and can change everything in the memory.
  • It can move the memory management to a caller, making a function more general.

Disadvantages:

  • In the C programming language, you can always pass an array to a function, however, you cannot return arrays from functions in the same way.
  • It may require an argument other than the declared to communicate the array size.
  • It misunderstands the argument in the documentation.

Passing an array to a function is like a simple and, any programmer familiar with the concept can quickly implement it. Although one must remember that an array passed to function uses the ‘pass by reference’ concept.

Pin It on Pinterest

Share This