Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

function to print min and max value of an array using c++ pointers

I’m trying to understand pointers in c++ so I made a function that takes an array and the length of that array and print out the min and max values of that array, however, it always just print the last element in that array for both min and max, I went through my code line by line but I still don’t understand the reason for this behavior, can you please help understand and fix my code, thanks.

void getMinAndMax(int numbers[], int length)
{
  int *min = &numbers[0];
  int *max = &numbers[0];
  cout << length << endl;
  for (int i = 1; i < length; i++)
  {
    if (*min > numbers[i])
    {
      *min = numbers[i];
    }
    if (*max < numbers[i])
    {
      *max = numbers[i];
    }
  }
  cout << "min: " << *min << endl;
  cout << "max: " << *max << endl;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since, you are using the de-referencing operator in the if condition. You are basically changing the value at the memory location where the pointer is pointing (in this case the 0th index of the array). What you should do in the if condition is store the index where the minimum and maximum values are present.
Like so

if (*min > numbers[i])
{
min = &numbers[i];
}

This way, the pointer will hold the addresses of the maximum and minimum values and when you dereference them, you will get the right answer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading