在问答上看到一个问题,本着赚金币的态度就回答了一下。话说遇到我这样的小白会的问题的几率真心不大,赶紧答一个。
C++中strcmp和 ==的比较问题
c++strcmp
char *str1 = “hello”;
char str2[] = “hello”;
if (str1 == “hello”)
printf(“ok1\n”);
if (str2 == “hello”)
printf(“ok2\n”);
if (strcmp(str1, “hello”))
printf(“ok3\n”);
if (strcmp(str2, “hello”))
printf(“ok4\n”);
输出结果是ok1,为什么呢?
为了更好地看到比较结果,我改写了程序:
include”stdio.h”
include”string.h”
main()
{
char *str1 = “hello”;
char str2[] = “hello”;
printf(“%d\n”,str1 == “hello”);
printf(“%d\n”,str2 == “hello”);
printf(“%d\n”,strcmp(str1,”hello”));
printf(“%d\n”,strcmp(str2,”hello”));
}
输出结果是1,0,0,0,说明
1. str2 == “hello”是不成立的。字符串的比较不能用==
2. strcmp(str1,”hello”),strcmp(str2,”hello”)都是成立的,因为成立的时候strcmp里边两个参数相等的时候值为0
由于”hello”是字符串常量,编译器会进行优化:
所有的”hello”都是相同的,整个程序中只需要有一个”hello”字符串。然后所有引用”hello”这个字符串的“指针变量”都赋值成相同的地址。所以:
char *str1 = “hello”;和”hello”的地址是相同的。
对于:char str2[] = “hello”;,这里str2并不是指针,类型里已经说明它是一个数组,所以这会是另一个内存地址,于是str2与”hello”的地址是不同的。