C Program–Passing an entire array to a function

/*

This program is to pass the entire array to a function

*/

#include <stdio.h>
#include <conio.h>
int maximum(int[],int); //function prototype, 1st parameter is array and the second is integer

int main()
{
    int a[100],i,n,max=0;
    printf("Enter the numbers"); 
    scanf("%d",&n); //get the index number
    for(i=0;i<n;i++) //get the array elements
    {
    scanf("%d",&a[i]);
    }
    max=maximum(a,n); //function call
    printf("Maximum number is %d",max);
    getch();
    return 0;
}

int maximum(int b[],int a) //function implementation
{
    int i,max=b[0];
    for(i=0;i<a;i++)
    if(b[i]>max)
    max=b[i];
    return max;
}

In the function call ie

max=maximum(a,n) where a is the array and n is the number of array elements

the above line can be written as

max = maximum(&a[0],n)

since the array is just a memory address, it is enough to mention the base address (address of the first element) of the array

so the array name is just equivalent to the base address

in the above example

a means &a[0]

Comments

  1. please give some more examples and details

    ReplyDelete

Post a Comment

Popular Posts