C Programming language

adplus-dvertising
Passing Arrays as Function Arguments in C
Previous Home Next

Can we pass an array to a function just like we pass any variable ?

The answer to the above question is definitely YES, we can pass array to function just like we pass any other variable. But the only difference would that the array is passed via call by reference method inside the function as we know that array as itself like a pointer in which base element acts like a pointer for the entire array

Just like any other normal we can pass an array to a function as :

void funarr(int arr[])

The above function funarr accepts an array of integers as its parameter. For passing the array as function we must declare array as,

int arr[10];

Equivalently we can also pass only the name of the array as parameter in the calling function as

void funarr(arr);

The following code snippet will demonstrate how can we pass array as a parameter to a function :

#include <stdio.h>
#include<conio.h>
void funarr(int arr[], int len)
{
printf("\nEnter the length of array :");
scanf("%\nd",&len);
printf("\nEnter the elements of the array :");
for(i=0; i<len; i++)
{
     scanf("%d",&arr[i]);
}
printf("\nThe elements of the array are as follows :");
for(i=0; i<len; i++)
{
    printf("\n%d",arr[i]);
}
}
void main()
{
int myarr[100];
clrscr();
funarr(myarr, 7);
getch();
}

Output : The output of the following program will be as follow :

Enter the length of array :

7

Enter the elements of the array :

1

3

4

5

3

2

6

The elements of the array are as follows :

1

3

4

5

3

2

6

Previous Home Next