Hello James,
The first thing to know about C is that it doesn't have a built in string type, and strings are in fact an array of chars (characters). When you define a string type you use
char* s;
which is a pointer to a memory location containing an array of chars. If you use a constant string like "-watts" then C will represent this as an array of chars (char[]) internally. No even though the contents of the memory pointed at by the char* and the contents of the array might be the same the variables them self are a pointer (an int internally) and an array of chars. Hence you get your error when trying to compare the pointer (char*) to the constant string (char[]).
The only way to compare strings is the way that you have done, using strncmp.
If you don't want to use strcmp then you could use characters as the first argument rather than strings, though you would have to dereference the argc pointer.
i.e. if (*(argc[1]) == 'w') {} else if (*(argc[1] == 'v') {}
Hope this helps.
Torben
On 16 May 2010 02:04, James Bensley jwbensley@gmail.com 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!