0

Possible Duplicate:
Passing an array as an argument in C++
Sizeof an array in the C programming language?

Can you please explain the output of the following code:

#include<iostream>
using namespace std;

void foo(int array[])
{
    int size = sizeof(array) / sizeof(array[0]);    
    cout<<size<<endl;
}
int main()
{
    int array[] = {1,2,3};

    int size = sizeof(array) / sizeof(array[0]);
    cout<<size<<endl;
    foo(array);
    return 0;
}

The corresponding output is:

3
2

Both the code inside foo() and inside main() looks similar to me so as to produce the same output, but it does not, can you please explain why?

Community
  • 1
  • 1
Nilanjan Basu
  • 828
  • 9
  • 20

2 Answers2

4
void foo(int array[]) 

in C or C++ you cannot pass arrays by value, so the above declaration is interpretted as:

void foo(int * array)

Consider passing the array by reference:

template <size_t N>
void foo( int(&array)[N] )
{   
    cout << N << endl;
}
Andrzej
  • 5,027
  • 27
  • 36
3

You are not passing the array into the function, you are passing the pointer to the array.

That means, in the function foo(), the result of sizeof(array) is the size of a pointer to an array of char, not the size of the array itself, so the function is effectively doing this:

cout << sizeof(int *) / sizeof(array[0]);

In this case size of int * is 8, size of int is 4, so you are getting an output of 2 from the function.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • The array elements are `int`, not `char`. Doesn't change the point, but you should still correct it. (`sizeof(char*) != sizeof(int*)` is allowed.) – Daniel Fischer Jul 13 '12 at 08:25
  • @DanielFischer, right, thanks! For some reason I thought it was 'char array[]' instead of 'int array[]' in OP's post – SingerOfTheFall Jul 13 '12 at 08:29