0

I'm trying to make method has an array as parameter the purpose of this method is to get the min element in the array. I'm using C++.

when I pass the array size using (sizeof(arr) / sizeof(arr[0]) to Loop it only has 2 as it's size

Here is my program :

int main(int argc, char** argv) {   
    
    int lenghtSticks;
    cout << "Enter [ N ] For length of sticks :\n";
    cin >> lenghtSticks;
    
    int sticksItems[lenghtSticks];
    
    for (int i = 0; i < sizeof(sticksItems) / sizeof(sticksItems[0]); i++)
         cin >> sticksItems[i];
        
        
        cout << minStick(sticksItems) << endl;
        
    return 0;
    } 

Here is my method

int minStick(int arr[]) {
    
    int lowest = arr[0];
    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
        if (lowest > arr[i])
        lowest = arr[i];
    }
    
    return lowest;
} 

Input as size of array [6] Input as Elements = {5, 4, 4, 2, 2, 6} I should get out put 2 but I get 4 any help

  • 3
    `int sticksItems[lenghtSticks];` is not standard C++. Use a `std::vector` – 463035818_is_not_an_ai Aug 18 '22 at 09:21
  • `int minStick(int arr[])` is the same as `int minStick(int* arr)`. `sizeof(arr)` is the size of a `int*` – 463035818_is_not_an_ai Aug 18 '22 at 09:22
  • When passing `arr` to the function `minStick`, `arr` will [decay](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) to a pointer to the first element of the array. Therefore, when using the expression `sizeof(arr)` in the function `minStick`, that expression will be the size of the pointer, not that of the array that it is pointing to. If you want the function `minStick` to know the size of the array, then you will have to pass the size of the array as an additional function argument. Otherwise, the function `minStick` has no way of determining the size of the array. – Andreas Wenzel Aug 18 '22 at 09:23
  • Really in C++ you should no longer use arrays like this. Just use std::vector, or std::array. Also these kinds of problems have solution in STL for you, something like this: `std::vector values{1,2,3}; auto it = std::min_element(values.begin(),values.end()); return *it;` No need to write buggy code yourself. – Pepijn Kramer Aug 18 '22 at 10:30
  • You can use [std::size(arr)](https://en.cppreference.com/w/cpp/iterator/size) to compute the size. It either gets the correct size when it can, or a compile time error otherwise, – BoP Aug 18 '22 at 10:30
  • @BoP I'm not a big fan of that either. Either use STL containers (dynamic) or template functions that resolve to fixed sized arrays at compile time. – Pepijn Kramer Aug 18 '22 at 10:32

0 Answers0