1

In the following working code; instead of using *tofind, if I directly use the comparison

if(*argv[i] == "and")

it fails.

Why would that be?

/**
* Find index of the word "and"
* ./a.out alice and bob
*/
int main(int argc, char **argv) {
    int i = 0;
    char *tofind = "and";
    while (argv[i] != NULL) {
        if(*argv[i] == *tofind) {
            printf("%d\n", i + 1);
            break;
        }
        ++i;
    }
    return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
  • you can directly compare `char` not string for string compare use `strcmp` look more http://www.cplusplus.com/reference/cstring/strcmp/ – Jayesh Bhoi Mar 04 '14 at 11:49

3 Answers3

2

if(*argv[i] == "and") shouldn't compile, I think you mean if (argv[i] == "and"), that would compare the pointers of the two, not the string content.

if (*argv[i] == *tofind) doesn't work as you expected either, it only compares the first character.

To compare strings, use strcmp():

if (strcmp(argv[i], tofind) == 0)
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

A "char*" is officially a pointer to a single char, for example to find points to a letter 'a'. You know that there are two more chars and a nul char, but officially it points to a single char.

Therefore, *argv[i] is the first character of an argument, and *tofind is always the letter 'a', so your code checks if the first character of an argument is an 'a'. Look at the strcmp function, which compares whole strings.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

look at the type of

*argv[i] //its type is char

and of "and"

"and" //its type is const char * as it is decayed into pointer

so thats why you are unable to compare them. while the type of

*tofind 

is char and you can now compare the two.for more details see FAQs section 6.

OldSchool
  • 2,123
  • 4
  • 23
  • 45