使用 strcmp() 函数时逻辑混乱

Confusion about logic when using strcmp() function

char string1[10];
char string2[10];

strcpy(string1, "hello");
strcat(string2, string1);

if(strcmp(string1, string2)){
   printf("Heellloww!!!);
} else {
   printf("Bye");
}

当我对 if(strcmp(string1, string2)) 执行检查时,那么 strcmp() return 应该做什么?为了在 if 中执行语句,它应该总是 return 正 1 吗?

经常查看手册:

int strcmp(const char *s1, const char *s2);

Return value: The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

在您的情况下,如果 string1string2 相同(或匹配),strcmp returns 为零。因此,如果它们 相同,您将打印 Bye,如果它们不同,则您将打印 Heellloww.

您的代码的问题是 strcat:它导致 未定义的行为

为了使 strcat 起作用,传递给它的两个字符串都必须以 null 结尾。但是,您传递的第一个字符串 不是 以 null 结尾的 - 实际上,它是未初始化的。

解决此问题很简单 - 您可以在声明时将零放入 string2 的初始位置:

char string2[10] = { 0 };

现在字符串将比较相等,这意味着 strcmp 将 return 为零。如果要在两个字符串相同时打印 Heellloww,则需要将 == 0 添加到 if 语句中。