[英]Invalid Operands to binary Expression, C
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 *')
二进制表达式的操作数无效('double *'和'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.
}
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, ie the address of the pointers will be compared. 例如
&pA[i] > ...
将导致指针比较,即将比较指针的地址 。 Most likely not what you want. 很可能不是你想要的。
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
. 您对
&pA
使用似乎非常困惑,指针min
和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. 如果你有一个指向值的指针(如
double *min
),那么*min
是你访问(读或写)指向的值的方式。
There is no "pass by reference" in C language unlike C++. 与C ++不同,C语言中没有“通过引用传递”。 You should dereference each pointer in your code if you want work with variables values.
如果要使用变量值,则应取消引用代码中的每个指针。 Now you work with variables addresses.
现在使用变量地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.