template <class T>
int get_array_length(T arr[])
{
return (sizeof(arr)/sizeof(T));
}
Because when passing the array name I'm really just passing a pointer to the array instead of the actual array. So "sizeof(arr)" is just like "sizeof(T*)".
But how should I fix this so that the function does what it's supposed to do?
I'm not sure that you can. Why do you need this function? When dealing with arrays in C++ you are dealing with pointers to a block of memory. std::vector would make your job much easier since it knows how big it is. If you really need a c array then you'll have to keep track of the length and pass it to function. I don't believe there is a way to determine the length of an array when all you have is a pointer to the first element.
// This works only for fixed-length arrays
template< typename T, size_t N >
size_t get_array_size( T (const &)[ N ] )
{ return N; }
// Some versions of GCC don't like the const in the above; you might
// need the non-const version:
// This works only for fixed-length arrays
template< typename T, size_t N >
size_t get_array_size( T (&)[ N ] )
{ return N; }