About Lesson
C Arrays & Function
In this tutorial, we will learn to pass element of arrays (both one-dimensional and multidimensional arrays) to a function using different methods in C programming with the help of examples.
Passing array to function using call by value method
- we can pass arrays as an argument to a function just like we pass variables as argument. And, also we can return arrays from a function.
- In order to pass array to the function we just need to mention the array name during function call.
- Before you learn about passing arrays as a function argument, make sure you know about C Arrays and C Functions.
Syntax
The syntax for passing an array to a function is:
returnType functionName(dataType arrayName[arraySize]) {
// statement
}
Let’s see an example,
int total(int num[2]) {
// statement
}
Here, we have passed an int
 type array named num to the function total()
. The size of the array is 2.
Example : Call by Value method
#include <stdio.h>
void num_print(int num){
  printf("Age is %d\n", num);
}
int main(){
  int age[] = {12, 38, 15, 62, 56, 23, 4, 12};
  // Passing all elements to of array age[] to num_print()
  for(int i = 0; i < 8; i++) {
    num_print(age[i]);
  }
  return 0;
}
Output
Age is 12
Age is 38
Age is 15
Age is 62
Age is 56
Age is 23
Age is 4
Age is 12
Passing array to function using call by reference method
In this method, we pass the address of an array/element while calling function.
When we pass an address as an argument, the function declaration receive the passed address with a pointer.
Syntax :
Data_type function_name(int array_name[size_of_array]) {
.
.
.
}
Example : Call by Reference method
#include <stdio.h>
void num_print(int *num){
  // Printing the element using the their address
  printf("Age is %d\n", *num);
}
int main(){
  int age[] = {12, 38, 15, 62, 56, 23, 4, 12};
  // Passing all elements to of array age[] to num_print()
  for(int i = 0; i < 8; i++) {
  // Passing the address of the element to the function
    num_print(&age[i]);
  }
  return 0;
}
Output
Age is 12
Age is 38
Age is 15
Age is 62
Age is 56
Age is 23
Age is 4
Age is 12
Note:Â In C programming, we cannot return arrays from functions but we can pass arrays to functions.