0

I am confused with how array is passed to the function. In this code..

#include <iostream>

using namespace std;

void func(int arr[])
{
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << n << endl;
}

int main()
{
    int arr[] = {3,6,2,4,7,9,5,1};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << n << endl;
    func(arr);
    return 0;
}

The output I am getting is

8

1

Can someone please explain why this is so?

Ankit Gupta
  • 757
  • 7
  • 13

1 Answers1

0

When an array is passed to a function it automatically decays to a pointer. Although you write int arr[] as an argument, arr is a pointer and sizeof(arr) yields sizeof(T*). Dereferencing a int* yields int. On your machine int* and int happen to have the same size, so sizeof(int*) / sizeof(int) == 1.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67