Cant Workout Why this C Condition Fails
I have a problem with some C code I am writing as part of a University assignment. Consider the code:
printf("%s\n", argv[1]);
if ((argv[1] == "--verbose") || (argv[1] == "-v")) {
printf("%d\n", argc);
}
now: printf("%s\n", argv[1]); prints "--verbose" so I know 开发者_如何学编程argv[1] == "--verbose" should be true, but the line printf("%d\n", argc); never executes. And I cant workout why. Any ideas?
Use the strcmp function:
strcmp(argv[1], "--verbose") == 0
== checks that two pointers have the same address, which is not what you want.
Refer to Wikipedia Article on strcmp.
Key here is you cannot compare strings directly with the == operator in C. This will only compare the pointers to the strings, which will be different.
Because you can't compare strings with == in C. Use strcmp or similar.
Shouldn't you be using strcmp to compare strings? Surely argv[1] == "--verbose" will not compare for equality of the strings to the letter.
In your code you are actually comparing the contents of the argv[1] pointer (which points to the string containing the first argument of your program) with the address of each string literal ("-v" etc). This is guaranteed to be false in all cases.
You should use the strcmp() function or similar to compare the strings themselves, rather than their addresses.
加载中,请稍侯......
精彩评论