当您使用指针执行== 时(这两种情况下str1 和str2 都是1),您所做的只是比较两个地址,看看它们是否是相同的。当你这样做时
char str1[]="hello";
char str2[]="hello";
您正在堆栈上创建两个包含"hello" 的数组。它们肯定位于不同的内存位置,所以str1 == str2 是false。这就像
char str1[6];
str1[0] = 'h';
str1[1] = 'e';
str1[2] = 'l';
str1[3] = 'l';
str1[4] = 'o';
str1[5] = '\0';
// and the same thing for str2
当你这样做时
char *str1="hello";
char *str2="hello";
您正在创建两个指向全局数据"hello" 的指针。编译器看到这些字符串字面量是一样的,不能修改,就会让指针指向内存中的同一个地址,str1 == str2就是true。
要比较两个char*s 的内容,请使用strcmp:
// strcmp returns 0 if the two strings are equal
if (strcmp(str1, str2) == 0)
printf("Equal");
else
printf("Not equal");
这大致相当于
char *a, *b;
// go through both strings, stopping when we reach a NULL in either string or
// if the corresponding characters in the strings don't match up
for (a = str1, b = str2; *a != '\0' && *b != '\0'; ++a, ++b)
if (*a != *b)
break;
// print Equal if both *a and *b are the NULL terminator in
// both strings (i.e. we advanced a and b to the end of both
// strings with the loop)
if (*a == '\0' && *b == '\0')
printf("Equal");
else
printf("Not equal");
1 在
char* 版本中,这是真的。在
char[] 版本中,
str1 和
str2 实际上是
数组,而不是指针,但是当在
str1 == str2 中使用时,它们会衰减为指向数组第一个元素的指针,所以它们在那种情况下相当于指针。