Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

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

How arrays are passed to function | Basic and Important

Introduction:

Source code

Idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
//#include <stdio.h>

using namespace std;

// Note that arr[] for fun is just a pointer even if square
// brackets are used
void fun(int arr[]) // SAME AS void fun(int *arr)
{
unsigned int n = sizeof(arr)/sizeof(arr[0]);
//printf("\nArray size inside fun() is %d", n);
//printf("\n - The first value is %d", sizeof(arr));

cout << "nArray size inside fun() is " << sizeof(arr)/sizeof(arr[0]) << endl;
}

// Driver program
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);
//printf("\n - The first value is %d", sizeof(arr));
cout << "nArray size inside main() is " << sizeof(arr)/sizeof(arr[0]) << endl;
fun(arr);
return 0;
}