比较c中的两个相等数组但输出显示不相等

Udi*_*pta 4 c arrays string pointers c99

经过长时间休息,我回到了C,但即使在一些简单的问题上也会感到困惑.所以一个人在这里.

这是简单的代码:

 #include<stdio.h>

 int main() {

    char str1[]="hello";
    char str2[]="hello";

    if(str1==str2)
            printf("equal");  
    else
            printf("unequal");
} 
Run Code Online (Sandbox Code Playgroud)

产出: 不平等

但是当我尝试这个时,它起作用了

  char *str1="hello";
  char *str2="hello";
Run Code Online (Sandbox Code Playgroud)

输出 相等

如果有人能提供详细的解释,请.谁能告诉我C99标准究竟是怎么说的?

Set*_*gie 12

当你==使用指针(这是str1str2在两种情况下1)你正在做的是比较两个地址,看看他们是相同的.当你这样做

char str1[]="hello";
char str2[]="hello";
Run Code Online (Sandbox Code Playgroud)

您正在堆栈上创建两个数组"hello".他们当然在不同的存储位置,所以str1 == str2false.这就像

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
Run Code Online (Sandbox Code Playgroud)

当你这样做

char *str1="hello";
char *str2="hello";
Run Code Online (Sandbox Code Playgroud)

您正在创建两个指向全局数据的指针"hello".看到这些字符串文字是相同的并且无法修改的编译器将使指针指向内存中的相同地址,并且str1 == str2true.

要比较两个s 的内容char*,请使用strcmp:

// strcmp returns 0 if the two strings are equal
if (strcmp(str1, str2) == 0)
    printf("Equal");
else
    printf("Not equal");
Run Code Online (Sandbox Code Playgroud)

这大致相当于

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");
Run Code Online (Sandbox Code Playgroud)


1char*版本中,这是真的.在char[]版本中,str1并且str2实际上是数组,而不是指针,但是当使用str1 == str2它们时,它们会衰减到指向数组的第一个元素的指针,因此它们相当于该场景中的指针.