0

i have written the following code. The std::size() function ist executing properly in the main() function but not in the getMin() function. Why?

#include <iostream>

int getMin(int numbers[]) {
    int temp = numbers[0];
    int sizeA = std::size(numbers);
    for (int i = 1; i < sizeA; i++) {
        if (temp > numbers[i])
            temp = numbers[i];
    }
    return temp;
}

int main()
{
    int numbers[5] = { 5, 5, -2, 29, 6 };

    std::cout << getMin(numbers) << " with Size of "<< std::size(numbers) << std::endl;

    std::cin.get();
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 3
    Inside `getMin`, `numbers` is not an array; it's a pointer. – Pete Becker Jun 15 '21 at 17:11
  • Further reading: [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – user4581301 Jun 15 '21 at 17:12
  • Change `int getMin(int numbers[])` to be `int getMin(int numbers[], size_t sizeA)` and call it with `getMin(numbers, std::size(numbers))`. – Eljay Jun 15 '21 at 17:30
  • 1
    Or use a container like [`std::array`](https://en.cppreference.com/w/cpp/container/array) that knows its size. – user4581301 Jun 15 '21 at 17:54
  • `std::size()` returns a value of type `std::size_t`. It's not a good idea to assign it to an `int` variable. – Evg Jun 15 '21 at 18:01
  • 1
    Or make `getMin()` into a template function so you can pass in any sized array by reference: `template int getMin(int (&numbers)[N]) { return *std::min_element(numbers, numbers+N); }` – Remy Lebeau Jun 15 '21 at 19:41

0 Answers0