0

why the number of elements in an array is calculate incorrect when passing an array to a function; They don't work, but why, and what works without passing the quantity as a parameter.

int foo(int arr[])
{
   return         sizeof(arr)/sizeof(arr[0]
}

int foo2(int arr[])
{
 int len = 0;

 for(auto i: arr)

 {

 len++

 }
 return len;
 }

☝️This function dont return correct

  • 1
    Not possible. [The array has decayed to a pointer](https://stackoverflow.com/q/1461432/4581301), so `sizeof` is providing the size of the pointer. You need to pass in the size, use a smarter data structure that carries the size like `std::array` or `std::vector`, or define [a template function](https://stackoverflow.com/q/968001/4581301). – user4581301 Apr 17 '23 at 20:15
  • 1
    you can forget about `sizeof` to calcuate the size of an array. When you really have to determine the size of a c-array use `std::size` – 463035818_is_not_an_ai Apr 17 '23 at 20:21
  • Use `std::vector`. A vector maintains its capacity. You can pass it by reference or const reference. – Thomas Matthews Apr 17 '23 at 20:44

0 Answers0