Solving C Compile Error: "Invalid Operands

  • Thread starter Thread starter kbaumen
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
kbaumen
Messages
190
Reaction score
0
Hi.

I'm kinda learning C at home by myself and was just to compile another small program when I encountered problem with compiling.

Here's the code:
Code:
#include <stdio.h>
#include <math.h>

int main(int argc, char **argv)
{
    float p, S;

    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <side_a> <side_b> <side_c> \n", argv[0]);
    }

    p = (argv[1] + argv[2] + argv[3]) / 2;                                //13th line
    S = sqrt(p * (p - argv[1]) * (p - argv[2]) * (p - argv[3]));   //14th line

    printf("Area of this triangle is: %f \n", S);

    return 0;
}

and here are the lines from compiler:
Code:
kbau@kbox:~/prj/c/test/exercises$ gcc uzd1.c -o uzd1 -Wall
uzd1.c: In function ‘main’:
uzd1.c:13: error: invalid operands to binary +
uzd1.c:14: error: invalid operands to binary -
uzd1.c:14: error: invalid operands to binary -
uzd1.c:14: error: invalid operands to binary -

I'm getting frustrated why isn't this working. I don't understand why is there a problem.

I don't really have any work to show you except the code, I'm just curious why isn't it working. Help would be appreciated.
 
Last edited:
Physics news on Phys.org
argv[n] is not a number. It is a char *-- a "string", a series of typed ASCII characters. In order to treat a string like a number, you must first convert it from a "string" to a number. See the man pages for atoi() and atof().
 
Coin said:
argv[n] is not a number. It is a char *-- a "string", a series of typed ASCII characters. In order to treat a string like a number, you must first convert it from a "string" to a number. See the man pages for atoi() and atof().

Yeah, I figured that out when I woke up during the night but thanks anyway. atof() is the one I need 'cause I have a float there.
 
Actually atof returns a double, not a float. Most compilers will "promote" the double to a float for you.

The reason I mention this - there are a lot of standard C functions that look like they might return a float - modf, atof, for example - when they return a double instead. You need to be careful about assuming what some C function returns just by the name of the function.
 
Ok, thanks, I'll keep that in mind.