简体   繁体   English

使用strcmp比较字符数组和字符指针

[英]comparing character array and character pointer using strcmp

int main(void) {
    char s[] = "ab";
    char *s1 = "ab";

    if(strcmp(s, s1))
        printf("%d", 24);
    else
        printf("%d", 23);

    return EXIT_SUCCESS;
}

Why it is giving 23 answer? 为什么给出23个答案?

This is because strcmp returns 0 if strings are equal. 这是因为如果字符串相等,则strcmp返回0 0 is treated as false in C. 0在C中被视为false

strcmp(string1, string2)

Return Value 返回值

if Return value < 0 then it indicates string1 is less than string2

if Return value > 0 then it indicates string2 is less than string1

if Return value = 0 then it indicates string1 is equal to string2  

strcmp returns 0 if the given strings are equal, as in this case. 如果给定的字符串相等,则strcmp返回0,在这种情况下。 0 is converted to false , so the else block is executed, printing 23 . 0转换为false ,因此执行else块,打印23

strcmp on success returns 0 . 成功的strcmp返回0 Hence if will fail. 因此, if失败。

Change if statement as, if语句更改为

if(strcmp(s , s1) == 0)

如果两个字符串比较相等,则strcmp返回0。

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

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