If I write
int main()
{
int a[100] = {1,2,3,4,};
cout<
The function does not know the array size in your example because you took explicit steps to convert your array to pointer type, thus completely stripping the function parameter of its original array nature. Once again, you yourself took deliberate steps to make sure that the function does not know the size of the array. Under these circumstances, it is rather strange to see you ask the question about why the function doesn't know the array size.
If you what the function to receive its argument as an array, you have to pass it as an array, not as a mere pointer, and declare the corresponding function parameter accordingly. Arrays in C++ cannot be passed "by value", which means that you'll have to pass it "by reference", as one possibility
void func(int (&a)[100])
{
cout << sizeof a / sizeof a[0] << endl;
}
sizeof
returns the size of the type. In the second example, func( int *a )
, a is a pointer and sizeof
will report it as such. Even if you did func( int a[100] )
, a would be a pointer. If you want the size of the array in func, you must pass it as an extra argument.