C等于常量字符串

时间:2014-11-23 06:42:47

标签: c

以下比较是否保证为 true

"hello world"=="hello world";

此外,以下始终保证 false

char a[] = "hello world";
a == "hello world";

4 个答案:

答案 0 :(得分:8)

要清楚 - 在这两种情况下,您都在比较指针,而不是实际的字符串内容。

"hello world"=="hello world";

允许比较为truefalse。 C标准在6.4.5“字符串文字”中说:

  

如果这些数组的元素具有适当的值,则未指定这些数组是否是不同的。

因此,该标准允许文字的存储相同或不同。

对于

char a[] = "hello world";
a == "hello world";

比较将始终为false,因为数组a的地址必须与字符串文字的地址不同。

答案 1 :(得分:1)

在C中你必须使用一个比较字符串的函数。直线走动只会告诉你两个字符串是否在内存中的相同位置。 所以

char a[] = "hello world";
char b[] = a;

制作

a == b;

会给你真实,因为a和b都指向内存中的相同位置或字符串。

如果你想比较两个字符串,你必须使用strcmp(),如果字符串相等则返回0。

if( strcmp(a, b) == 0 )
    printf("True\n");
else
    printf("False\n");

要使用它,您需要包含库string.h。

#include <string.h>

答案 2 :(得分:0)

C中的==运算符不允许比较字符串内容。 你应该使用

strcmp(str1,str2);

在这种情况下,您正在比较指针。 所以

"hello world" == "hello world";

可能是也可能不是。

但第二种情况总是假的。

char a[] = "hello world";
a == "hello world";

答案 3 :(得分:0)

C中的

==运算符可用于比较原始数据类型。由于String在C中不是原始的,因此您无法使用==来比较它们。最好的选择是通过包含strcmp()库来使用string.h功能。

相关问题