0

I am trying to make my own function that takes a double array and returns maximum index. But when I run the code to check the function with a random array below, it returns 0 when it's supposed to return 9. When I run the same exact code inside the function in main, it works. What's wrong with my code that is working in main() but not when used inside a function?

int findMaxIndex(double array[]) {
    int maxIndex=0;
    int arraySize = sizeof(array)/sizeof(array[0]);
    for (int i=0;i<arraySize;i++) {
        if (array[maxIndex]<array[i]) {
            maxIndex=i;
        }
    }
    return maxIndex;
}

int main() {
    double array[10] = 
{11.20,22.2,33.3,43.4,55.5,66.6,77.7,88.8,90.0,100};

    cout <<findMaxIndex(array)<<endl;

    return 0;
}
  • This: `int findMaxIndex(double array[])` is exactly the same as this: `int findMaxIndex(double* array)` -- That's why the `sizeof` thing you're doing inside the function doesn't work as you thought it would. – PaulMcKenzie Jun 17 '22 at 17:20
  • Use `std::array` or `std::vector` if the size is determined at runtime – MatG Jun 17 '22 at 18:58

0 Answers0