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;
}
1

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.