On 16/05/10 02:04, James Bensley wrote:
Hey List,
I have what is hopefully a beginners C question which will be easily answered (this following little app is for converting watts, amps and volts);
I have the following code: http://pastebin.com/m30x4G17
The problem I have is although the code works, it is because I have used the strncmp function to compare the first pasted argument and a string value such as "-watts", "-volts" or "-amps" because without it I was getting errors about comparing integers and pointers but I am confused as to why C thinks this.
Using if(argv[1]=="-watts") produces no errors but the if statements are never hit, as in the if statement is never met and the code is never run. How should I be coding this to make these comparisons?
Just to add a little to what others have said, == simply compares two numbers. In your fragment
argv[1] == "-watts"
The 'number' on the LHS is the address of the string passed on the command kine and the 'number' on the RHS is the address in memory of the string literal "-watts". Clearly these two addresses will never be the same so your if statement always fails.
Incidentally, this is such a common requirement ISTR there are some library functions that do these tests for you but I cannot for the life of me remember where they are!
Cheers
Ian