I am trying to figure out how i get the length of an array in c without iterate over all index. The function looks like this:
template<typename T>
void linearSearch(T arr[], int n)
{
}
CodePudding user response:
You can't. T arr[]
as argument is an obfuscated way to write T* arr
, and a pointer to first element of an array does not know the arrays size.
If possible change the function to pass the array by reference instead of just a pointer:
template <typename T, size_t N>
void linearSearch(T (&array)[N], int n);
Things get much simpler if you use std::array
.
PS: As a comment on the question suggests, the question is not quite clear. Is this the function you want to call after getting the size or do you need to get the size inside this function? Anyhow, I assumed the latter and that n
is a argument unrelated to the arrays size. Further note that there is std::size
that you can use to deduce the size also of a c-array. However, this also only works with the array, not once the array decayed to a pointer (as it does when passed as parameter to the function you posted).