Passing Array as Function Argument in C

In C language we can pass one-dimensional array as an argument in a function. To pass the array as formal parameter we have to declare a formal parameter for array at the time of function declaration. There are three ways to do this :

1. Formal parameter as an Array :
void MyFunc( int arr[]);
The function call will be look like this :
MyFunc( num );
Where the num is the name of array, means we just need to provide the name of array and not the size of array.

Now lets see an example :
 #include <stdio.h>

void printArr(int arr[], int size);

int main() {
  int num[5] = {10, 20, 30, 40, 50};
  printArr(num, 5);
  return 0;
}

void printArr(int arr[], int size) {
  int x;
  for(x=0;x<size;x++) {
    printf("%d\n", arr[x]);
  }
}
Output :

10
20
30
40
50

At the above example, the function  printArr() is called with the array name arr and the size of the array, 5.

2. Formal parameter as a Pointer :
void MyFunc( int *arr);
Where  the pointer arr points to the supplied.

Example :
#include <stdio.h>

void printArr(int *arr, int size);

int main() {
  int num[5] = {10, 20, 30, 40, 50};
  printArr(num, 5);
  return 0;
}

void printArr(int *arr, int size) {
  int x;
  for(x=0;x<size;x++) {
    printf("%d\n", arr[x]);
  }
}
Output :

10
20
30
40
50


Next Topic :