The function parameter has a pointer type
int len(int *thing) {
return sizeof(thing) / sizeof(int);
}
Even if you will rewrite the function like
int len(int thing[]) {
return sizeof(thing) / sizeof(int);
}
nevertheless the compiler will adjust the array type of the function parameter to the type pointer to the array element type as written in the first function declaration.
So within the function the expression sizeof(thing)
yields the size of a pointer. If the size of a pointer is equal to the value of sizeof( int )
then the function returns 1.
You could write instead
template <size_t N>
size_t len(const int ( &thing )[N] ) {
return N;
}
and then
cout << len(fard);
to get the number of elements in the array fard
.
Pay attention to that there is already standard C++ function std::size
declared in the header <iterator>
in C++ 17.
So you could write
#include <iterator>
//...
std::cout << std::size(fard);