Reputation: 99
Im working on a function that takes some values and finds the min, max, and average of the values. I'm passing everything to the function by reference and am getting some errors when I try and do basic operations like +
and /
Namely the error is
Invalid operands to binary expression ('double *' and 'double *')
void MinMaxAvg(double *pA, double *min, double *max, double *avg, int lines, double *total )
{
for (int i=0; i<lines; i++)
{
if ( i==0)
{
min = &pA[0];
max = &pA[0];
}
else
{
if (&pA[i] < min)
{
min = &pA[i];
}
if (&pA[i] > max)
{
max = &pA[i];
}
}
total += &pA[i]; //<-- Errors on this line
}
avg = (total / lines); // <-- Errors on this line.
}
Upvotes: 3
Views: 54395
Reputation: 532
There is no "pass by reference" in C language unlike C++. You should dereference each pointer in your code if you want work with variables values. Now you work with variables addresses.
Upvotes: 1
Reputation: 980
It seems like you're getting some of the types confused there. In your example you're setting the pointers to a new value, not the value of said pointers.
The first would have to be:
*total += pA[i];
While the second should be:
*avg = (*total / lines);
In fact, you probably want to use floating point division on the second error there (some compilers are notorious for using integer divison in unexpected places):
*avg = (*total / (double)lines);
You'll still be getting errors if you do it like that, however. For example &pA[i] > ...
will result in a pointer comparison, i.e. the address of the pointers will be compared. Most likely not what you want.
Upvotes: 5
Reputation: 399813
You're trying to add an address to a pointer, that's not a valid operation.
You probably meant:
*total += pA[i];
Your use of &pA
seems very confused, as does the re-assignment of the pointers min
and max
.
If you have a pointer to a value (like double *min
), then *min
is how you access (read or write) the value being pointed at.
Upvotes: 2