Javatpoint Logo
Javatpoint Logo

Passing Array to Function in C

In C, there are various general problems which requires passing more than one variable of the same type to a function. For example, consider a function which sorts the 10 elements in ascending order. Such a function requires 10 numbers to be passed as the actual parameters from the main function. Here, instead of declaring 10 different numbers and then passing into the function, we can declare and initialize an array and pass that into the function. This will resolve all the complexity since the function will now work for any number of values.

As we know that the array_name contains the address of the first element. Here, we must notice that we need to pass only the name of the array in the function which is intended to accept an array. The array defined as the formal parameter will automatically refer to the array specified by the array name defined as an actual parameter.

Consider the following syntax to pass an array to the function.

Methods to declare a function that receives an array as an argument

There are 3 ways to declare the function which is intended to receive an array as an argument.

First way:

Declaring blank subscript notation [] is the widely used technique.

Second way:

Optionally, we can define size in subscript notation [].

Third way:

You can also use the concept of a pointer. In pointer chapter, we will learn about it.


C language passing an array to function example

Output

minimum number is 3

C function to sort the array

Output

Printing Sorted Element List ...
7  
9  
10  
12  
23 
23  
34  
44  
78  
101  

Returning array from the function

As we know that, a function can not return more than one value. However, if we try to write the return statement as return a, b, c; to return three values (a,b,c), the function will return the last mentioned value which is c in our case. In some problems, we may need to return multiple values from a function. In such cases, an array is returned from the function.

Returning an array is similar to passing the array into the function. The name of the array is returned from the function. To make a function returning an array, the following syntax is used.

To store the array returned from the function, we can define a pointer which points to that array. We can traverse the array by increasing that pointer since pointer initially points to the base address of the array. Consider the following example that contains a function returning the sorted array.

Output

Printing Sorted Element List ...
7  
9   
10  
12  
23 
23  
34  
44  
78  
101  
Next TopicC Pointers


Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA