c++ - 我怎样才能通过引用传递这个指针?

标签 c++ pointers pass-by-reference

指针和引用是新手,所以我不太确定这一点,但我正在尝试传递指针 *minDataValue 和 *maxDataValue,以便在它们从函数返回时更改它们的值。截至目前,在代码中,它们的值没有改变(从测试代码可以看出),我如何设置它们以及我必须更改什么才能使它们通过引用传递以便值可以在函数时更改已经完成了。谢谢!

 void findMinAndMax(int array[], int size, int *min, int *max) {

  int smallest = array[0];
  int largest = array[0];

  min = &smallest;
  max = &largest;

  for (int i = 1; i < size; i++)
  {
    if (array[i] > largest){
      largest = array[i];
    }
    if (array[i] < smallest){
      smallest = array[i];
    }
  }

  // testing code
  cout << *min << endl;
  cout << *max << endl;

}

int *makeFrequency (int data[], int dSize, int *minDataValue, int    *maxDataValue) {

   cout << *minDataValue << endl;// testing code
   cout << *maxDataValue << endl;// testing code

   findMinAndMax(data, dSize, minDataValue, maxDataValue); // How do I pass this so that the value changes after the min and max are found? 

   cout << *minDataValue << endl; // testing code
   cout << *maxDataValue << endl;// testing code

}

int main() {

int dSize;
int *ArrayOfInts;

  cout << "How many data values? ";
  cin >> dSize;

  ArrayOfInts = new int [dSize];

  getData(dSize, ArrayOfInts);

  int *frequency, min, max;

  frequency = makeFrequency(ArrayOfInts, dSize, &min, &max);
 }

最佳答案

You have to use pointer of pointer or pass by reference (@Sami Sallinen explained) to change the value *minDataValue and *maxDataValue inside the functions

//Using pointer of pointer
void findMinAndMax(int array[], int size, int **min, int **max)
{
  int *smallest = &array[0];
  int *largest = &array[0];

  min = &smallest;
  max = &largest;

  for (int i = 1; i < size; i++)
  {
    if (array[i] > *largest){
      *largest = array[i];
    }
    if (array[i] < *smallest){
      *smallest = array[i];
    }
  }

  // testing code
  cout << **min << endl;
  cout << **max << endl;
}

int *makeFrequency (int data[], int dSize, int *minDataValue, int    *maxDataValue)
{
findMinAndMax(data, dSize, &minDataValue, &maxDataValue); 
}

关于c++ - 我怎样才能通过引用传递这个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077089/

相关文章:

c++ - 初始化列表模板变量

pointers - 范围内的 golang 指针不起作用

python - 我可以获得在 Python 2.7 中引用其他变量的列表吗?

java - 将类枚举传递给克隆是否克隆安全?

c++ - C++ 中的 ReadFile 崩溃

c++ - C++中纯虚方法的重新定义

c++ - 如何处理长溢出

c++ - C++ 中 void 指针的缺点

c++ - const 引用函数参数 : Is it possible to disallow temporary objects?

C# ArrayList.Add 方法向项目添加引用?