Passing Arrays to Function - C Tutorial

Passing Arrays to Function

Passing One dimensional Arrays to Function

When an entire array is passed to a function, however, it is always passed by reference.

when an entire array is passed to a function, and the function changes variables stored in that array, it does affect the data in the calling function's array.

Because arrays are passed by reference, there is generally no need for a function to "return" an array.

In order to prevent the function from changing the array values, the array parameter can be modified with the keyword const.

When an entire array is passed to a function, the size of the array is usually passed as an additional argument.

Example - Passing One dimensional Arrays to Function

#include 
int maxArrayOne(int arr[],int size)
{
    int max,i;
    max=arr[0];
    for(i=0;i< size;i++) 
    {
          if(max< arr[i])
                max=arr[i];
    }
    return max;
}

int maxArrayTwo(int *arr,int size)
{
    int max,i;
    max=arr[0];
    for(i=0;i<size;i++)
    {
            if(max<arr[i])
                max=arr[i];
    }
    return max;
}

int main()
{
    int arr[]={10,2,44,5,6};
    int size=5,max,i;
    printf("Array Elements....\n");
    for(i=0;i<size;i++)
        printf("%d ",arr[i]);

    max=maxArrayOne(arr,size);
    printf("\nMaximum in Array :%d",max);

    max=maxArrayTwo(arr,size);
    printf("\nMaximum in Array :%d",max);


    return 0;
}
Output - Passing One dimensional Arrays to Function
Array Elements....     
10 2 44 5 6            
Maximum in Array :44   
Maximum in Array :44