strcmp 和双相等关系运算符在 C 中不起作用

mhk*_*mhk -1 c string string-comparison

在 C 中使用以下程序,字符串比较不起作用:

#include<stdio.h>
#include<string.h>
int main(){
    char ch[]="ABC";
    printf("%d \n", strlen(ch));    // output 3
    printf("%d \n", strlen("ABC")); // output 3
    if(strcmp("ABC",ch)){
        printf("\n Matched");
    }else{
        printf("\n Not matched"); // this will be output
    }

    if("ABC" == ch){
        printf("\n Matched");
    }else{
        printf("\n Not matched"); // this will be output
    }
}//ends main
Run Code Online (Sandbox Code Playgroud)

输出是:

3

3

 Not matched

 Not matched
Run Code Online (Sandbox Code Playgroud)

为什么字符串不匹配?

Som*_*ude 8

随着"ABC" == ch你比较两个三分球,你不比较什么指针指向。而这两个指针永远不会相等。

如果字符串相等,则该strcmp函数返回。零在 C 中被认为是“假”,所有非零值都是“真”。


C 中的字符串文字实际上是(只读)字符数组,包括终止符。由于所有数组在大多数表达式中使用时,它们都会衰减为指向其第一个元素的指针。