Array using function

Passing an array into a function is like passing an argument in a variable. We know that the array name contains the address of the first element. Therefore, we simply pass the array name as the argument. This concept is employed in two methods:

  • Passing array using call by value.
  • Passing array using call by reference.

Passing array using call by value

First, we need to understand two points: Actual parameters are the parameters of the calling function, and Formal parameters are the parameters of the called function. It's important to note that it's not compulsory for actual parameters and formal parameters to be the same; they may be the same or different.

Syntax of calling function

Let us soppose we have a array function 'arr' name then and Array name is 'array'.

int array[20];
arr(array);
Syntax of called function
void arr(int array[])
{
   //statement
}
Example
#include<stdio.h>
void arr(int arr[],n)
{
   int i,sum=0;
   for(i=0;i<i++)
   {
    sum=sum+arr[i];
   }
   printf("%d",sum);
}
int main()
{
	int n,array[100],i;
    printf("Enter Number of element in array=");
	scanf("%d",&n);
	printf("Enter Elements=");
	for(i=0;i<n;i++)
	{
     scanf("%d",&array[i]);
    }
	array(array,n);
	return 0;
 }

Passing array using call by reference

When we pass the address of an Array while calling a function then this is called function call by reference. When we pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed address.

Syntax of calling function

Let us soppose we have a array function 'arr' name then and Array name is 'array',

   int array[20];
   arr(&array);
Syntax of called function
void arr(int *array)
{
   // statement
}
Example
#include<stdio.h>
void display(int *arr)
{
    printf("%d",*arr);
}
int main()
{
	int array={0,9,8,7,6,5,4,3,2,1},i;
	for(i=0;i<10;i++)
	{
     display(&arr[i]);
    }
	return 0;
}
   
The Output is:0,9,8,7,6,5,4,3,2,1.

Summary

  • Passing Arrays: Arrays can be passed to functions as arguments, enabling the function to operate on the array's elements.
  • Array Size: When passing an array to a function, its size is not explicitly specified; instead, the function receives a pointer to the array's first element.
  • Modifying Arrays: Functions can modify array elements passed as arguments, and these modifications will persist after the function returns.
  • Returning Arrays: C does not allow functions to return arrays directly, but functions can return pointers to arrays or dynamically allocated arrays.
  • Array as Return Type: Alternatively, functions can modify arrays passed as pointers or receive arrays as pointers and directly manipulate their elements.