0

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;
}
5
  • post your current code so we can help u. Commented Aug 7, 2017 at 23:58
  • 5
    Without some code it is hard to tell what you are asking, but isn't it just return &array[minIndex]; ? Commented Aug 7, 2017 at 23:58
  • 2
    A week into two different languages at once? Wow. Personally, I'd pick one. Commented Aug 8, 2017 at 0:01
  • 1
    C and C++, despite their superficial similarities, are very, very different languages. Don't confuse the two. Commented Aug 8, 2017 at 0:07
  • Totally understand that C and C++ are different. As I said, I have some sense for how to accomplish this in C++ using std::min_element. But also need to do this in C. Commented Aug 8, 2017 at 0:17

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.