C

Example Of Passing An Array To A Function In C Programming

Arrays, like variables, can be passed as arguments to functions. We will learn how to pass an array to a function using the call by value and call by reference methods in this guide.
To understand this guide, you should be familiar with the following C programming topics:

  1. Array (C)
  2. C function call by value
  3. In C, a function is called by reference.

Using the call by value method, an array is passed to a function

As we already know, the actual parameter is copied to the formal parameters in this type of function call.

#include <stdio.h>
void disp( char ch)
{
   printf("%c ", ch);
}
int main()
{
   char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
   for (int x=0; x<10; x++)
   {
       /* I’m passing each element one by one using subscript*/
       disp (arr[x]);
   }

   return 0;
}

Output:

a b c d e f g h i j

Using call by reference to pass an array to a function

When we pass the address of an array to a function, we are using function call by reference. When an address is passed as an argument, the function declaration should include a pointer as a parameter to receive the address.

#include <stdio.h>
void disp( int *num)
{
    printf("%d ", *num);
}

int main()
{
     int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
     for (int i=0; i<10; i++)
     {
         /* Passing addresses of array elements*/
         disp (&arr[i]);
     }

     return 0;
}

Output:

1 2 3 4 5 6 7 8 9 0

How do I pass an entire array as an argument to a function?

In the preceding example, we used a for loop in C to pass the address of each array element one by one. You can, however, pass an entire array to a function like this:
Take note that the array name is the address of the array’s first element. For example, if the array name is arr, then arr is equivalent to &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
	/* The pointer var1 is pointing to the first element of
	 * the array and the var2 is the size of the array. In the
	 * loop we are incrementing pointer so that it points to
	 * the next element of the array on each increment.
	 *
	 */
    for(int x=0; x<var2; x++)
    {
        printf("Value of var_arr[%d] is: %d \n", x, *var1);
        /*increment pointer for next element fetch*/
        var1++;
    }
}

int main()
{
     int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
     myfuncn(var_arr, 7);
     return 0;
}

Output:

Value of var_arr[0] is: 11 
Value of var_arr[1] is: 22 
Value of var_arr[2] is: 33 
Value of var_arr[3] is: 44 
Value of var_arr[4] is: 55 
Value of var_arr[5] is: 66 
Value of var_arr[6] is: 77

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button