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?
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 ofsizeof(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:In this case size of
int *is 8, size of int is 4, so you are getting an output of 2 from the function.