指针和引用是新手,所以我不太确定这一点,但我正在尝试传递指针 *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/