为什么直接比较字符串失败,但成功使用char *

在以下工作代码中; 如果我直接使用比较,而不是使用*tofind

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

它失败。

那为什么会这样?

 /** * 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; } 

if(*argv[i] == "and")不应该编译,我认为你的意思if (argv[i] == "and") ,它将比较两者的指针,而不是字符串内容。

if (*argv[i] == *tofind)也没有按预期工作,它只比较第一个字符。

要比较字符串,请使用strcmp()

 if (strcmp(argv[i], tofind) == 0) 

“char *”正式指向单个字符的指针,例如查找字母“a”的点。 你知道有两个字符和一个零字符,但正式它指向一个字符。

因此,* argv [i]是参数的第一个字符,* tofind始终是字母’a’,因此您的代码会检查参数的第一个字符是否为’a’。 查看strcmp函数,它比较整个字符串。

看看的类型

 *argv[i] //its type is char 

和“和”

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

这就是为什么你无法比较它们。 而类型

 *tofind 

是char,您现在可以比较两者。有关详细信息,请参阅常见问题解答第6节。