Passing Array to Function in C Language with Free Notes

Passing One Dimensional Array to a Function

Like other type of arguments, Array elements can also be passed to a function by calling the function by value or by reference.

In call by value method we pass the values of array elements to the function whereas in call by reference we pass addresses of array elements to the function e.g.

Example: Pass Individual elements of an array to a function one by one i.e. (call by value)/

#include <stdio.h>
#include <conio.h>
void main()
{
  void show(int);
  int m [] = {50,60,70,40,90,80}, i;
  clrscr();
     for (i=0; i<6; i++)
        show (m [i]);
        getch();
    }
     void show(int marks)
           {
              printf("\t%d", marks);
           }

Output

50  60  70  40  90  80
Free E-books

Same Problem using call by reference

void main()
{
  void show(int*);
  int m [] = {50,60,70,40,90,80}, i;
  clrscr90;
     for (i=0; i<6; i++)
        show (m + i);
    }
     void show(int *marks)
           {
              printf("\t%d", *marks);
           }

Passing Entire Array to Function

In place of passing individual elements of an array one by one to a function, we can also pass an argument array to a function.

It can be implemented by the following:

Example: Passing Entire Array

#include <stdio.h>
#include <conio.h>
void main()
{
  void show(int*, int);
  int m [] = {50,60,70,40,90,80};
  clrsc();
   show(m, 6); // m is the starting address of an array
        getch();
    }
     void show(int *marks, int n)
           {
             int i;
             for(i=0; i<n; i++)
                {
                   printf("\t%d", marks);
                   marks++;
                 }
            }

Passing Two Dimensional Array to Function

Elements of two dimensional array can be passed to a function in the same form as that of one dimensional array.

Example: Demonstration of passing d-dim array elements to a function

#include <stdio.h>
#include <conio.h>
void main()
{
  void show(int[][], int, int);
  int a [3][4] = {
                   {1,2,3,4},
                   {5,6,7,8},
                   {9,10,11,12},
                 };
                  clrsc();
                  show(a,3,4,);
                   getch();
                }
              void show (int n [][4], int r, int c)
                  {
                     int i, j;
                     for (j=0; i<c; j++)
                          printf("%d\t", n[i][j]);
                     printf("\n";
                 }
            }

Leave a Comment

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

Scroll to Top