1

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)
{
}
  • Does this answer your question? [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – Lala5th Apr 12 '22 at 12:55
  • Is that function where want to determine the array's length, or a function you want to call after finding the length? – Spencer Apr 12 '22 at 12:55
  • @VNVNA That's for a `std:array` not a C-style array as in the question. – Spencer Apr 12 '22 at 12:56
  • Alternatively you can do `template void func(T (&arr)[N], int n)` – Lala5th Apr 12 '22 at 12:57
  • When u pass an array to a function like that, you must provide a size for it. `void linearSearch(T arr[], size_t size, int n)` – VN VNA Apr 12 '22 at 12:57

1 Answers1

8

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).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185