Friday, November 5, 2010

Passing array to function in C Language

In the next example we will store some values in an array and the address of each location of the array will be passed to a function one after another . The function will display the value stored in the location.

#include< stdio.h>
 void dis(int *);
void main()
{
 int i;
 int arr[]={3,4,5,6};
 for(i=0;i< 4;i++)
 dis(&arr[i]);
 }
 void dis(int *p)
 {
 printf("\nValue=%d",*p);
}

Now the same program is modified so that  the entire array is passed to the function at a time.

#include<stdio.h>
 void dis(int *,int);
void main()
{
  int arr[]={3,4,5,6};
  dis(&arr[0],4);
 }
 void dis(int *p,int no)
 {
 int i;
 for(i=0;i< no;i++)
 {
 printf("\nValue=%d",*p);
 p++;
 }
}


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner