Function question

Hi,

Following is the program to calculate the array length:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void fun(int a[])
{
    int size = sizeof(a)/sizeof(int);
    cout << "In function " << size << endl;
}

int main()
{
        int a[]={0,1,2,3,4,5,6};
        int size = sizeof(a)/sizeof(int);
        cout << "In main " << size << endl;
        fun(a);
        return 0;
}

The output I get is:

In main 7
In function 1

Could someone please help me why is this difference?

Thanks
In c++ you don't pass arrays, you pass pointers to the first element. So sizeof(a) is sizeof(int*) in fun() and sizeof(int[7]) in main().
Last edited on
As I understand, an array name, 'a' in the above program is nothing but the address of the 1st element, i.e. &a[0].

So in the main program, isn't sizeof(a) /sizeof(int) same as sizeof(&a[0])/sizeof(int) which should be 1 ? Why is it 7 ?

Thanks for your reply.
Last edited on
a is a pointer of type int. The content of a is the address of a[0].
Last edited on
Hello,

I just wanted to know why in the main program, the output is 7 ?
Since a is nothing but &a[0].
So sizeof(&a[0])/sizeof(int) should be 1.

Thank you.
Once a gets passed into a function it changes types.

In main(), it is of type int[7].

In fun(), it is of type int*.

Maese909 wrote:
The content of a is the address of a[0].

Incorrect. In the function fun(), the content of a, that is, if you did *a, is a[0].
Thanks for the reply shacktar !!
Now my doubt is cleared.

Thanks once again.
Topic archived. No new replies allowed.