How arrays are passed to functions in C/C++


In this tutorial, we will be discussing a program to understand how arrays are passed to functions.

In the case of C/C++, the arrays are passed to a function in the form of a pointer which provides the address to the very first element of the array.

Example

 Live Demo

#include <stdio.h>
//passing array as a pointer
void fun(int arr[]){
   unsigned int n = sizeof(arr)/sizeof(arr[0]);
   printf("\nArray size inside fun() is %d", n);
}
int main(){
   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
   unsigned int n = sizeof(arr)/sizeof(arr[0]);
   printf("Array size inside main() is %d", n);
   fun(arr);
   return 0;
}

Output

Array size inside main() is 8
Array size inside fun() is 2

Updated on: 17-Feb-2020

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements