C Passing Array to Function


To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

Syntax

functionname(arrayname); //passing array  

There are 3 ways to declare function that receives array as argument.


First way to declare function that receives array

Formal parameters as a sized array.

void myFunction(int param[10])
{
.
.
.
}

Second way to declare function that receives array

Formal parameters as a pointer.

void myFunction(int *param)
{
.
.
.
}  

Third way to declare function that receives array

Formal parameters as an unsized array.

void myFunction(int param[])
{
.
.
.
}

Example

#include <stdio.h>
int main(){
   float a[2][2], b[2][2], c[2][2];
   int i,j;
   printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there was an array of 'n' dimension, 'n' numbers of loops are needed for inserting data to array.*/   
   for(i=0;i<2;++i)      
       for(j=0;j<2;++j){
       printf("Enter a%d%d: ",i+1,j+1);
       scanf("%f",&a[i][j]);
       }
   printf("Enter the elements of 2nd matrix\n");
   for(i=0;i<2;++i)
       for(j=0;j<2;++j){
       printf("Enter b%d%d: ",i+1,j+1);
       scanf("%f",&b[i][j]);
       }
   for(i=0;i<2;++i)
       for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using loop. */
       c[i][j]=a[i][j]+b[i][j];  /* Sum of corresponding elements of two arrays. */
       }
   printf("\nSum Of Matrix:");
   for(i=0;i<2;++i)
       for(j=0;j<2;++j){
       printf("%.1f\t",c[i][j]);  
           if(j==1)             /* To display matrix sum in order. */
              printf("\n");
      }
return 0;
}
Output
Enter the elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;

Enter the elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2     0.5
-0.9    25.0

Share this article on