c语言 - == 在比较 argv[] 字符串时不起作用



我注意到,使用strcmp和==运算符比较普通字符串变量和字符串都有效,但使用==比较argv字符串不起作用,只适用于strcmp。为什么?什么特别?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]) {
char *tempStr = "string";
int x = atoi(argv[2]), y = atoi(argv[3]);

if (strcmp(tempStr, "string") == 0) {
printf("'strcmp' methods works in case comparing with normal string variablen");
}
if (tempStr == "string") {
printf("'strcmp' as well as '==', both the methods works in case comparing with normal string variablen");
}

/* this works for argv[] strings*/
if (strcmp(argv[1], "add") == 0) printf("%d", x + y);
else if (strcmp(argv[1], "subtract") == 0) printf("%d", x - y);
else if (strcmp(argv[1], "multiply") == 0) printf("%d", x * y);
else if (strcmp(argv[1], "divide") == 0) printf("%d", x / y);

// /* this doesn't works for argv[] strings */ 
// if (argv[1] == "add") printf("%d", x + y);
// else if (argv[1] == "subtract") printf("%d", x - y);
// else if (argv[1] == "multiply") printf("%d", x * y);
// else if (argv[1] == "divide") printf("%d", x / y);
return 0;
}

使用==时,它比较的是地址,而不是内容。您将tempStr声明为指向字符串文字的指针,并将其与同一字符串文字进行比较。编译器注意到文字是相同的,所以它为它们使用了相同的内存,这使得地址相同。

你不能指望这是真的,将这些类似的字符串组合在一起是编译器的优化。

如果您将申报更改为

char tempStr[] = "string";

使用CCD_ 3不会得到相同的结果。在这种情况下,tempStr是本地数组,而"string"是静态字符串文字,它们将位于不同的内存位置。

此比较

char *tempStr = "string";
//...
if (tempStr == "string") {
printf("'strcmp' as well as '==', both the methods works in case comparing with normal string variablen");
}

可以计算为逻辑true或逻辑false,具体取决于编译器选项,该选项确定编译器是将相同的字符串文字存储为一个字符串文字(字符数组(还是单独的字符数组。

关于这个比较

if (argv[1] == "add") printf("%d", x + y);

那么当比较两个指向占用不同内存范围的字符串的指针时,这样的比较总是评估为逻辑错误。

也就是说,在上面的比较中,数组指示符被隐式地转换为指向数组的第一元素的指针,并且指针被比较。

上面的if语句等价于下面的if语句

if ( &argv[1][0] == &"add"[0] ) printf("%d", x + y);

最新更新