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;
}
CodePudding user response:
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.