Passing array to a function in C Programming

  • An array can be passed to a function by using pointers.

  • Syntax:
    func(int arr[]);
    OR
    func(int *arr);

  • Whenever the name of the array is passed to the function, the address of the 0th element of the array is copied to the local pointer variable in that function.
  • On declaring a formal parameter in the function header as an array, it will be interpreted as a pointer to a variable and not an array.
  • With this all the elements of the array can be accessed by using the array_name+index.
For a function that accepts array as a parameter following syntax is used:

func (int arr[], int n);
OR
func(int *arr, int n);

Example : Swapping two numbers by using pointers & function

#include <stdio.h>
void swap(int *x,int *y);
void main()
{
    int n1=10,n2=20;
    swap(&n1,&n2);  /* address of n1 and n2 is passed to swap function */
    printf("Number1 = %d\n",n1);
    printf("Number2 = %d",n2);
}
void swap(int *x,int *y)  /* pointer x and y points to address of n1 and n2 respectively */
{      
     int t;
     t = *x;
     *x = *y;
     *y = t;
}


Output:
Number1 = 20
Number2 = 10