使用 C++ 指针打印数组的最小值和最大值的函数

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

我试图理解 C++ 中的指针,所以我创建了一个函数,它接受一个数组和该数组的长度并打印出该数组的最小值和最大值,但是,它总是只打印最后一个元素在最小值和最大值的数组中,我逐行检查了我的代码,但我仍然不明白这种行为的原因,请你帮助理解和修复我的代码,谢谢。

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;
}

因为,您在 if 条件中使用了 de-referencing 运算符。您基本上是在指针指向的内存位置更改值(在本例中为数组的第 0 个索引)。在 if 条件下您应该做的是存储存在最小值和最大值的索引。 像这样

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

这样,指针将保存最大值和最小值的地址,当您取消引用它们时,您将得到正确的答案。