On 16 May 2010, at 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?
-- Regards, James.
http://www.jamesbensley.co.cc/
main@lists.alug.org.uk http://www.alug.org.uk/ http://lists.alug.org.uk/mailman/listinfo/main Unsubscribe? See message headers or the web site above!
Using strncmp() is the Right Way.
You can't use '==' to compare strings in C, because a string literal is just syntactic sugar for a statically allocated char *. So what you're doing when you say 'if(argv[1]=="-watts")' is "allocate memory for the string "-watts", and see if argv[1] points to the same place". If you've got a sane C compiler, this is guaranteed not to be true.
DC.