为什么第一个代码输出在第二个代码中是false和true?

时间:2018-02-05 12:46:39

标签: c

代码1

#include<stdio.h>    

int main(){
const char st1[]={"Hello"};
const char st2[]={"Hello"};

if(st1==st2){
  printf("True");
}
else{
  printf("False");
}
return 0;
}

代码2

int main(){
const char *st1="Hello";
const char *st2="Hello";

if(st1==st2){
    printf("True");
}
else{
    printf("False");
}
return 0;
}

现在在第一个代码中char数组成为const。 在第一个代码中,我得到False作为optput。 在第二个代码中它是真的。 提前谢谢

3 个答案:

答案 0 :(得分:1)

== does not compare the string contents.

In the first snippet st1 are st2 char[6] types with automatic storage duration, and you are allowed to modify the string contents. When using == these types decay to char*. Their addresses must be different, so == will yield false.

In the second snippet, the string literals are read only, in C they are still formally char[6] (cf. C++ where they are const char[6] types) although the behaviour on attempting to modify the contents is undefined. Using const char* types for them is perfectly acceptable and reasonable. Because the contents are read only, the compiler might use the same string and so st1 and st2 might point to the same location in memory. In your case, that is happening, and the result of == is true.

答案 1 :(得分:-1)

The second is true because you are using an optimizing compiler. Since str1 and str2 are pointers, it makes them point to the same string, thus saving a little memory.

答案 2 :(得分:-2)

Totally wrong answer for both C and C++. Pls, vote for delete.