Search code examples
functionpointersintsyntax-errorprogram-entry-point

Invalid binary operands, missing theory


I am getting an error " invalid operands to binary * (have ‘double’ and ‘double *’)" I must use the function as its written with pointers though the variables for x,y are normal double, so i sent in their address to make the function work . I don't get why for slope there is no error but only for *y_intercept .

void determine_line(double *, double *, double *, double *, double *, double *);

int main()
{
    double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0, m = 0.0, b = 0.0;

    x1 = readValue("x1");
    y1 = readValue("y1");
    x2 = readValue("x2");
    y2 = readValue("y2");

    double *y_intercept = &b;
    double *slope = &m;

    determine_line(&x1,&y1,&x2,&y2,slope,y_intercept);
    printf("\nThe points (%.2lf, %.2lf) and (%.2lf, %.2lf) are on the"
        " line: y = %.2lfx + %.2lf\n",x1,y1,x2,y2,*slope,*y_intercept);
}
void determine_line(double *x1, double *y1, double *x2, double *y2
, double *slope, double *y_intercept)
{
    *slope = (y1-y2)/(x1-x2);
    *y_intercept = y2 - (*slope) * x2 ; // error
}

Solution

  • All the arguments to determine_line are pointers. You need to dereference the pointers to get the numbers that you can perform arithmetic on.

    You don't get an error for the *slope assignment because pointer subtraction is allowed, although in this case the results are undefined because the pointers don't point to the same objects. But that line also needs dereferencing as well to produce the correct result.

    void determine_line(double *x1, double *y1, double *x2, double *y2
    , double *slope, double *y_intercept)
    {
        *slope = (*y1-*y2)/(*x1-*x2);
        *y_intercept = *y2 - (*slope) * *x2 ;
    }
    

    It's not clear why the first 4 arguments are pointers in the first place, though. The only arguments that need to be pointers are slope and intercept, since they're used to send the results back.