deserthiker
deserthiker

Reputation: 67

Address of minimum value in an array in C/C++

Just a week into C/C++. I have a function that takes a pointer to an array as an argument. Manipulating this input array inside the function results in a change in another (globally defined) array. I need to find and return the address of the minimum value in this (globally defined) array of floats. In C++ I can do this relatively easily with std::min_element(), since this returns an iterator. Any way to do this in C? I can write a loop to find the minimum value in an array, but not sure how to access its address? Here'e the (pseduo)code.

globalArray[100] = {0}
float *DoSomething(float *array)
{
    if (conditionMet == 1)
        { Do something to array that modifies globalArray;}
    float min;
    min = globalArray[0];
    for (int i = 0; i <100; i++)
    {
         if (globalArray[i] < min)
            min = globalArray[i];
    }
    return &min;
}

Upvotes: 0

Views: 839

Answers (1)

merlin2011
merlin2011

Reputation: 75575

You need to keep an extra variable around to track the index.

min = globalArray[0];
int minIndex = 0;
for (int i = 0; i <100; i++)
{
     if (globalArray[i] < min) {
        min = globalArray[i];
        minIndex = i;
     }
}
return &globalArray[minIndex];

Alternatively, you can use the extra variable to track the pointer.

min = globalArray[0];
float* minPointer = globalArray;
for (int i = 0; i <100; i++)
{
     if (globalArray[i] < min) {
        min = globalArray[i];
        minPointer = globalArray + i;
     }
}
return minPointer;

Upvotes: 4

Related Questions