简体   繁体   English

C strcmp-比较由char和char *声明的字符串

[英]C strcmp - compare strings declared by char and char*

I am trying to compare 2 strings using the below code: 我正在尝试使用以下代码比较2个字符串:

char a[100] = "\0";
char* b[10];
for (int i = 0; i < 10; i++)
    b[i] = "";
b[0] = "xy";
a[0] = 'x';
a[1] = 'y';
int c = strcmp(a, b[0]);

I think both a and b[0] contain the string "xy" , so I expect int c equal 0. However the result stored in int c is -858993460. 我认为ab[0]都包含字符串"xy" ,因此我希望int c等于0。但是存储在int c的结果是-858993460。 Why would that happen? 为什么会这样? What should I do in order to avoid this fault? 为了避免该故障我该怎么办? Thank you very much. 非常感谢你。

Update: I found that there is some error on my computer... 更新:我发现我的计算机上有一些错误...

char a[3] = { NULL };
char d[3] = { NULL };
a[0] = 'x';
a[1] = 'y';
a[2] = '\0';

d[0] = 'x';
d[1] = 'y';
d[2] = '\0';
int c = strcmp(a, d);

Even using this code, I got int c to be a negative value. 即使使用此代码,我也将int c设为负值。 I have no idea why that happened. 我不知道为什么会这样。

It is undefined behaviour because a is not null terminated. 这是未定义的行为,因为a不为空终止。 All string in C have to be null terminated to be used in strcmp . C中的所有字符串必须为null终止才能在strcmp What strcmp does is looping over the two strings until either one of the two is NULL terminated (see Implementation of strcmp to get an idea of how it works). strcmp作用是循环这两个字符串,直到两个字符串之一以NULL终止(请参阅strcmp的实现以了解其工作原理)。 You can see that if '\\0' is not present anywhere you got a problem there. 您可以看到,如果在任何地方都没有出现'\\0' ,那么您会遇到问题。

Read Why do strings in C need to be null terminated? 阅读为什么C中的字符串需要以null终止? for more info: 有关更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM